How to assign the domain name to the port in Docker

Viewed 1200

I mounted Laravel on port 80 in Docker and this is my service in docker-compose.yml

  webserver:
    image: nginx:alpine
    container_name: webserver
    restart: unless-stopped
    tty: true
    ports:
    - "8000:80"
    - "8443:443"
    volumes:
    - ./:/var/www/docker/example/api
    - ./nginx/conf.d/:/etc/nginx/conf.d/

I want to mapping 8000 port from ubuntu with 80 on docker that you see is done. and the site comes up with this address http://ip_server:8000

I want to come up with the domain name of the site without entering the port

server {
    listen 80;
    index index.php index.html;
    server_name example.com;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/docker/khesarat/api/public;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}
2 Answers

In this case and what I have done in my case is to run another nginx container listening on port 80. Add nginx and webserver containers to the same network, then you should see what you want.

Do as below:

  • Run docker network create NAME
  • Run `docker run -dp80:80 --network NAME -v /path/domain.conf:/etc/nginx/conf.d/ nginx:alpine
  • Create a domain.conf file like this:
server {
        listen 80;
        server_name DOMAIN;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://webserver:8000; # you also can remove :8000
        proxy_redirect off;

        # Socket.IO Support
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
  • Change your current docker-compose.yml to:
webserver:
    image: nginx:alpine
    container_name: webserver
    restart: unless-stopped
    tty: true
    ports:
    - "8000:80"
    - "8443:443"
    volumes:
    - ./:/var/www/docker/example/api
    - ./nginx/conf.d/:/etc/nginx/conf.d/
networks:
  default:
    external:
      name: NAME

In this case you also can remove ports mapping directive from your docker-compose file since it's not needed.

If I am not confused, you would have to map it to 80, and then edit your host file (depends on what OS you are in) and add 127.0.0.1 example.com and it will automatically resolve to it.

Related