4

I'm new to DockerFile. I want Nginx to be listening on port 8080. so I've written the dockerFile in this way:

FROM nginx:1.11-alpine
COPY index.html /usr/share/nginx/html
EXPOSE 8080
CMD ["nginx", "-g" , "daemon off;"]

but after making image and running container with this command:

docker run -d -p 80:8080 nginxt:v3

and Curl on localhost I'm getting this error :

curl: (56) Recv failure: Connection reset by peer

what am I doing wrong? EXPOSE 8080 doesn't mean that Nginx must be listened on 8080?

1 Answers1

4

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 a "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 executing envsubst 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;