Petr Hejda
Petr Hejda

Reputation: 43481

Docker-compose multiple services listen on same port, different domains

How can I have multiple docker services listening on same ports, only using different domains?

Is it even possible to define in docker-compose or do I need to have just one service listening on the port and then rerouting the traffic to respective services depending on the domain?


This example is failing since it's listening on the whole network (instead of just the domains)

docker-compose up
Creating network "test-docker_default" with the default driver
Creating test-docker_static_1 ... done
Creating test-docker_app_1    ... 
Creating test-docker_app_1    ... error

ERROR: for test-docker_app_1  Cannot start service app: driver failed programming external connectivity on endpoint test-docker_app_1 (ef433ffad1af01ffa31cd8a69a8c15b69ca7e7b6935924d34891b92682570e68): Bind for 0.0.0.0:80 failed: port is already allocated

ERROR: for app  Cannot start service app: driver failed programming external connectivity on endpoint test-docker_app_1 (ef433ffad1af01ffa31cd8a69a8c15b69ca7e7b6935924d34891b92682570e68): Bind for 0.0.0.0:80 failed: port is already allocated

docker-compose.yml

version: '3.3'
services:

  app:
    image: node
    depends_on:
      - static
    networks:
      default:
        aliases:
          - app.localhost
    ports:
      - 80:80

  static:
    image: nginx
    networks:
      default:
        aliases:
          - static.localhost
    ports:
      - 80:80

/etc/hosts

127.0.0.1    app.localhost
127.0.0.1    static.localhost

Upvotes: 2

Views: 8325

Answers (2)

Ben
Ben

Reputation: 159

You should use a reverse proxy. You can for instance give a look to jwlider/nginx on dockerhub.io, documentation is quite good !

Upvotes: 2

Cyril G.
Cyril G.

Reputation: 2017

You can map only one container to the same port of the host. If you want to map 2 services on same host port, you should use a reverse proxy like Traefik (well integrated with docker). The reverse proxy will listen the host port 80, then forward to a specific docker container on port not mapped to the host depending some defined rules like aliases, url path.

Upvotes: 5

Related Questions