I cannot figure out what is the problem with the official nginx image for docker. I use it in docker-compose.yml file as indicated on the official image page:
web:
image: nginx
volumes:
- ./custom-nginx.conf:/etc/nginx/conf.d/custom-nginx.conf
ports:
- "80:80"
environment:
- NGINX_HOST=mysite.com
- NGINX_PORT=80
command: /bin/sh -c "envsubst < /etc/nginx/conf.d/custom-nginx.conf > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"
custom-nginx.conf file looks like:
upstream app_server {
server 127.0.0.1:7999;
}
server {
listen ${NGINX_PORT};
server_name ${NGINX_HOST};
root /var/www/app/;
gzip_static always;
access_log /var/log/nginx/app.access.log;
error_log /var/log/nginx/app.error.log;
client_max_body_size 5000M;
proxy_connect_timeout 6000;
proxy_send_timeout 6000;
proxy_read_timeout 6000;
send_timeout 6000;
location / {
# checks for static file, if not found proxy to app
try_files $uri @proxy_to_app;
}
location @proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
# we don't want nginx trying to do something clever with
# redirects, we set the Host: header above already.
proxy_redirect off;
proxy_pass http://app_server;
}
location /media/ {
internal;
error_page 401 403 404 = @proxy_to_app;
}
location /favicon.ico {
alias ../static/favicon.ico;
}
}
But the corresponding docker container just exits upon starting alleging all kind of configuration errors that substitute each other in some random and unclear order despite my edits. Errors like duplicate upstream, invalid number of arguments in try_files
, missing env variables etc. I have found several sources on the internet describing similar problem, but what is suggested there didn't work out for me. I tried to remove upstream declaration in nginx custom config file, tried to indicate exact env. variable to substitute in docker-compose command for nginx image like $$NGINX_HOST
and \$NGINX_HOST
– no effect, just one error instead of another. So, how to make nginx container work properly with docker-compose.yml and config files I provided?
PS: docker logs -t cont_id
gives the same error: nginx: [emerg] invalid number of arguments in "try_files" directive in /etc/nginx/conf.d/default.conf
Best Answer
In case someone faces similar problem, I found out that it has to do with overriding environment variables here
command: /bin/sh -c "envsubst < /etc/nginx/conf.d/custom-nginx.conf > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"
. That's what other people wrote on the web, but all their suggestions didn't work out for me. I ended up removing this partenvsubst < /etc/nginx/conf.d/custom-nginx.conf > /etc/nginx/conf.d/default.conf &&
andenvironment:
section in docker-compose.yml, hardcoding host and port. It allowed nginx to start. Then I had an error here:It has to be the name of app container address inside docker network.