2

I would like to know how do we link webapp to database in docker swarm mode. I'm very new to docker swarm mode and had a basic cluster setup on my local machine. Any links would be great.

Example: Hosting a drupal application (Connected drupal cms containers with mysql database container).

Thanks

Swaroop Kundeti
  • 515
  • 4
  • 11
  • 25

2 Answers2

4

Correct, using custom networks is the way forward. A very simple example to get you started;

Create an "overlay" network (overlay networks allow containers to communicate, even if they are running on different nodes in the swarm);

docker network create --driver=overlay my-network

Create a database service named my-db, and attach it to the my-network network. There is no need to "publish" the database port, because drupal will connect with the database over the my-network network. Only publish database-ports if you want the database to be publicly accessible.

docker service create \
    --name=my-db \
    -e MYSQL_ROOT_PASSWORD=topsecret \
    -e MYSQL_DATABASE=drupal\
    -e MYSQL_USER=drupal-user \
    -e MYSQL_PASSWORD=secret \
    --network=my-network \
    mysql:5.7

Create a drupal service (named mysite), and also attach it to the same network. Publish the site's ports, because you want it to be publicly accessible

docker service create \
    --name=mysite \
    --network=my-network \
    --publish=8080:80 \
    drupal:8.2-apache

After the services are created, and the containers are running (you can check the status with docker service ls), you can visit <host-ip>:8080 in your browser. In swarm mode, <host-ip> can be the IP-address of any host in your swarm. The "routing mesh" will automatically route the network connection to the node that a container runs on.

Now, to configure drupal, using the username/password you set in MYSQL_USER and MYSQL_PASSWORD, and using my-db as hostname for the database (under advanced options) - when using docker networks, you can connect to other services on the same network through their name.

drupal configuration

This is just a very quick example. Some things to look into are;

  • Volumes (save uploads, and user-data in a volume, so that the information can persist when updating your container)
  • Secrets; passing username and password as environment variables is insecure. Docker 1.13 will introduce docker secrets, which allow you to pass the database credentials in a more secure way. Documentation is not live yet, but you can find them on GitHub
thaJeztah
  • 27,738
  • 9
  • 73
  • 92
2

using Links in docker is apparently more of a legacy why to connect to containers (although i still use this method myself)

The "new" way to do it is to use docker networks, you can read more about it here: https://docs.docker.com/engine/userguide/networking/get-started-overlay/

Hope this helps

Vade
  • 2,009
  • 6
  • 24
  • 32