Search code examples
dockerdocker-composedocker-network

Private "host" for docker compose network


Given a docker-compose file something like this

version: "3.8"
services:
  service-one:
    ports:
      - "8881:8080"
    image: service-one:latest
  service-one:
    ports:
      - "8882:8080"
    image: service-two:latest

what happens is that service-one is exposed to the host network on port 8881 and service-two would be exposed on the host network at port 8882.

What I'd like to be able to arrange is that in the network created for the docker-compose there be a "private host" on which service-one will be exposed at port 8881 and service-two will be exposed on port 8882 such that any container in the docker-compose network will be able to connect to the "private host" and connect to the services on their configured HOST_PORT but not on the actual docker host. That is, to have whatever network configuration that usually bridges from the CONTAINER_PORT to the HOST_PORT happen privately within the docker-compose network without having the opportunity for there to be port conflicts on the actual host network.


Solution

  • I tweak this to fit to your case. The idea is to run socat in a gateway so that containers nor images changed (just service names). So, from service-X-backend you are able to connect to:

    • service-one on port 8881, and
    • service-two on port 8882

    Tested with nginx containers.

    If you wish to make some ports public, you need to publish them from the gateway itself.

    version: "3.8"
    
    services:
    
      service-one-backend:
        image: service-one:latest
        networks:
          - gw
    
      service-two-backend:
        image: service-two:latest
        networks:
          - gw
    
      gateway:
        image: debian
        networks:
          gw:
            aliases:
              - service-one
              - service-two
        depends_on:
          - service-one-backend
          - service-two-backend
        command: sh -c "apt-get update
                     && apt-get install -y socat
                     && nohup bash -c \"socat TCP-LISTEN: 8881,fork TCP:service-one-backend:8080 2>&1 &\"
                     && socat TCP-LISTEN: 8882,fork TCP:service-two-backend:8080"
    
    
    networks:
      gw: