Search code examples
dockerdocker-swarm

Docker-machine swarm; how to open ports on VM


Trying out the new "swarm mode", following this. I have created 3 VM's via docker-machine create --driver virtual box <name>. But how do I open ports on them?


Solution

  • It might work with docker run -p <public-port>:<internal-port> <image> executed on the node. However, since you want to run a swarm, I guess it is better to follow a good guide to solve the routing mess here. If you follow the author's suggestions, you need to create a swarm (i.e. the docker host cluster) first by the docker-machine commands, e.g.

    docker-machine create --driver virtualbox swarm-1
    docker-machine create --driver virtualbox swarm-2
    

    setup swarm with

    eval $(docker-machine env swarm-1)
    docker swarm init --advertise-addr $(docker-machine ip swarm-1)
    

    join the other machines (if there are any) with

    eval $(docker-machine env swarm-2)
    docker swarm join \ 
    --token <yourtoken> 192.168.99.106:2377
    

    where <yourtoken>is found in the output of the docker swarm init command.

    Then the author suggests to create a network with something like

    docker network create --driver overlay webnet
    

    and publish the port by defining a service like

    docker service create --name webapp --replicas=2 --network webnet --publish 80:8000 <yourdockerimage>
    

    In this example, yourdockerimage is running a service internally on port 8000, which is mapped to the docker host port 80. Then, you can access the service e.g. by

    curl http://<IP-address of any Docker swarm node>:80
    

    Note, you can access the IP address of any Docker swarm node. Docker swarm will do the magic and will route the request to a container of this service, even if you have chosen the IP address of a node no container of this service is running on.