Connect an existing database from Docker network

To list Docker networks

docker network ls  

result:

NETWORK ID          NAME                DRIVER              SCOPE  
58fa29cd9897        bridge              bridge              local  
e6f07fb628ff        devvhosts_default   bridge              local  
1b20cf0e2660        host                host                local  
e24d89089238        none                null                local  

There are 3 pre-defined networks and cannot be removed:

  • bridge
  • host
  • none

To remove unused docker networks:
docker network rm $(docker network ls -q).

So the current running container would be devvhosts_default.

Which docker container runs my database:

docker ps  

result

CONTAINER ID        IMAGE                   COMMAND                  CREATED             STATUS              PORTS                           NAMES  
8b30b55fb76b        nginx:alpine            "nginx -g 'daemon off"   About an hour ago   Up 56 minutes       443/tcp, 0.0.0.0:8000->80/tcp   devvhosts_nginx_1  
c55d7a0d1ba7        php:5.6.23-fpm-alpine   "php-fpm"                About an hour ago   Up 56 minutes       9000/tcp                        devvhosts_fpm5-6-23_1  
7a398b243667        php:7.0.8-fpm-alpine    "php-fpm"                About an hour ago   Up 57 minutes       9000/tcp                        devvhosts_fpm7-0-8_1  
949e358c6309        phpmyadmin/phpmyadmin   "/run.sh"                About an hour ago   Up 57 minutes       0.0.0.0:8080->80/tcp            devvhosts_dbadmin_1  
29f4cad29bc0        harianto/mysql          "mysqld --skip-grant-"   About an hour ago   Up 57 minutes       3306/tcp                        devvhosts_db_1  

So it's devvhosts_db_1.

So my network would be --net devvhosts_default and the link as db would be: --link devvhosts_db_1:db.

I'll be using Alpine OS to run commands

docker run --rm --net devvhosts_default --link devvhosts_db_1:db -it alpine:latest /bin/sh  

Now I'm in the Alpine shell. Since there is no mysql client installed we can do by following command:

# install mysql-client
apk add --update mysql-client

# open mysql shell and connect to host 'db'
mysql -h db  
Welcome to the MariaDB monitor.  Commands end with ; or \g.  
Your MariaDB connection id is 38  
Server version: 10.1.14-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.  
MariaDB [(none)]> show databases;  
+--------------------+
| Database           |
+--------------------+
| information_schema |
| stuff              |
+--------------------+
2 rows in set (0.02 sec)

MariaDB [(none)]> \q  
Bye  
comments powered by Disqus