0

I am using docker-compose for my python web app. I am using nginx as one of service. Currently I am running on localhost and it is working fine. Now, instead of localhost I am trying to use domain name as server_name www.mywebapp.com and I also need to edit /etc/hosts file to add 127.0.0.1 www.mywebapp.com, Although file already has default entry as 127.0.0.1 localhost.

  • File: default.conf.template
server {
    
    listen 8080;
    server_name ${DOMAIN_NAME};

    client_max_body_size 8G;

    location / {       
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_http_version 1.1;
        proxy_pass http://web:5000;
    }
}
  • File: nginx Dockerfile
ARG NGINX_IMG
FROM $NGINX_IMG
ARG DOMAIN_NAME
ENV DOMAIN_NAME=$DOMAIN_NAME
USER root
# RUN sed -i 's/127.0.0.1       localhost/127.0.0.1       localhost $DOMAIN_NAME/' /etc/hosts
RUN echo "127.0.0.1       $DOMAIN_NAME" >> /etc/hosts 
COPY deploy/docker/proxy/default.conf.template /etc/nginx/conf.d/default.conf.template 
USER nginx
CMD ["/bin/sh" , "-c" , "envsubst '$DOMAIN_NAME' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"]

Output:

  • On running, sed it gives error as busy operation
  • On running, echo it executes successfully, but on checking from nginx container terminal cat /etc/hosts No modification for domain name
  • On checking default.conf the server_name gets updated by envbust as server_name www.mywebapp.com

As getting error to modify /etc/hosts file unable to access through domain name.

How to edit /etc/hosts file on nginx docker image?

winter
  • 467
  • 2
  • 10
  • 1
    The hosts file is one of the parts of network setup that's managed by Docker at container startup time; you can't modify it in your image, but the linked question describes options to add entries to it when you run the container. Consider whether an external DNS service would be more scalable and maintainable than trying to manually copy around `/etc/hosts` files. – David Maze Apr 10 '23 at 17:42
  • 1
    (Also remember that 127.0.0.1 in Docker is usually the current container; it is a different `localhost` than 127.0.0.1 on the host system.) – David Maze Apr 10 '23 at 17:42
  • Hi David, Thanks. I Agree, As I am new to DevOps and learning the deployment process, now exploring AWS. – winter Apr 11 '23 at 11:51

0 Answers0