Exposing another port for Nginx in DockerFile
By defining EXPOSE 8080
on your Dockerfile, you are only changing the exposed container port, but your Nginx server will still listen on port 80 (as it is configured by default).
You need to change the Nginx listen
configuration to match your new exposed port.
Different from mostly docker implementations, Nginx doesn't support such configs by using environment variables (see Using environment variables in Nginx configuration on their Docker Hub page).
If you wish to adapt the Nginx default configuration, you need to create a new nginx.conf
with the listen 8080;
config, then replace the original using COPY
in your Dockerfile.
If your prefer an "one-line workaround", you can change the command to replace the config on every start:
FROM nginx:1.11-alpine
COPY index.html /usr/share/nginx/html
EXPOSE 8080
CMD ["/bin/sh", "-c", "sed -i 's/listen .*/listen 8080;/g' /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"]
Update
Since version 1.19 Docker image Nginx will extract environment variables before it starts:
By default, this function reads template files in
/etc/nginx/templates/*.template
and outputs the result of executingenvsubst to /etc/nginx/conf.d.
So if you place
templates/default.conf.template
file, which contains variable references like this:
listen ${NGINX_PORT};
outputs to
/etc/nginx/conf.d/default.conf
like this:
listen 80;