Search code examples
phpsqlapachedockerhost

Access MySQL from 3 other docker containers


Currently I am trying to set up three different docker containers (php and apache) and let them listen to 4th in which my sql server is running. Does somebody know how can I get my mysql container listen to the 3 other containers?


Solution

  • Containers can interact with each other if they are attached to the same custom docker network. Networks provide "isolation" (i.e., only containers that are connected to the same network can interact), and if you've given your containers a name, containers are able to find each other using the container-name as hostname.

    While you can achieve similar results with the legacy --link option, --link

    For example;

    create a network for your application, called "private-net"

    docker network create private-net
    

    Start a MySQL container, named "db", and tell docker to connect it to the "private-net" network. Note that there is no need to "publish" port 3306 for other containers to connect to it; you should only publish (-p) a port if you want it to be publicly accessible (for example to make your web server accessible from the internet).

    docker run -d --name=db  --net=private-net -e MYSQL_ROOT_PASSWORD="secret" mysql
    

    Start your application container. Just to demonstrate the principle here; we're using a mysql container for this as well, but start it interactively with a shell session, to show how to connect to the database;

    docker run -it --name=app --net=private-net mysql bash
    
    root@fb5379f80508:/# # we're in the 'app' container
    root@fb5379f80508:/# # connect to the mysql container, using it's name ('db') as hostname
    root@fb5379f80508:/# mysql -h db -p
    Enter password:
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 4
    Server version: 5.7.17 MySQL Community Server (GPL)
    
    Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    mysql> \q
    Bye
    root@fb5379f80508:/# # exiting the container
    root@fb5379f80508:/# exit
    exit
    

    You can connect/disconnect containers from a network at runtime using the docker network connect and docker network disconnect commands. Containers can be connected to multiple networks, which can be useful if you have a service that is shared by multiple applications.

    For more information about Docker networks, read the documentation here: work with network commands