Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mulitple Docker Containers on Port 80 with Same Domain

My question is similar to this question but with only one domain.

Is it possible to run multiple docker containers on the same server, all of them on port 80, but with different URL paths?

For example:

Internally, all applications are hosted on the same docker server.

172.17.0.1:8080 => app1
172.17.0.2:8080 => app2
172.17.0.3:8080 => app3

Externally, users will access the applications with the following URLs:

www.mydomain.com                 (app1)
www.mydomain.com/app/app2        (app2)
www.mydomain.com/app/app3        (app3)
like image 857
Steve Avatar asked Apr 04 '16 02:04

Steve


People also ask

Can I run multiple Docker containers on same port?

Surprisingly or not, neither Docker nor Podman support exposing multiple containers on the same host's port right out of the box. Example: docker-compose failing scenario with "Service specifies a port on the host. If multiple containers for this service are created on a single host, the port will clash."

Is it possible to bind two containers on the same host port?

yes, it is possible as long as containers are using different IP address.

Can you have multiple Docker containers running?

Docker Compose is a tool that helps us overcome this problem and efficiently handle multiple containers at once. Also used to manage several containers at the same time for the same application. This tool can become very powerful and allow you to deploy applications with complex architectures very quickly.

How do I run a Docker container on port 80?

You can expose a port through your Dockerfile or use --expose and then publish it with the -p 80:80 flag. This will bind the exposed port to your Docker host on port 80, and it expects the exposed port is 80 too (adjust as necessary with HOST:CONTAINER ).


1 Answers

I solved this issue with an nginx reverse proxy.

Here's the Dockerfile for the nginx container:

FROM nginx
COPY nginx.conf /etc/nginx/nginx.conf

And this is the nginx.conf:

http {

        server {
              listen 80;

              location / {
                proxy_pass http://app1:5001/;
              }

              location /api/ {
                proxy_pass http://app2:5000/api/;
              }
        }
}

I then stood up the nginx, app1, and app2 containers inside the same docker network.

Make sure to include the trailing / in the location and proxy paths, otherwise nginx will return a '502: Bad Gateway'.

All requests go through the docker host on port 80, which hands them off to the nginx container, which then forwards them onto the app containers based on the url path.

like image 170
user326608 Avatar answered Nov 04 '22 18:11

user326608