Sharing a network between standalone Docker containers

If you have two, standalone Docker containers, how do you network between them? I have this setup:

  • php/apache
  • mariadb

Most of the information I could find on the Web was related to using the command line, or was totally inscrutable. I wanted to set this up in docker-compose.yml so that students could simply download the files and spin up the containers without worrying about configuration. So, for future reference:

You will have a docker-compose.yml file for each of the containers, and you need to simply add the shared network to each. In this case, we will create a shared network named phpdev:

container 1:

services:
  mariadb:
    image: "mariadb:latest"
    restart: 'always'
    ports:
      - '${LOCAL_MYSQL_PORT}:3306'
    volumes: 
      - ${LOCAL_MARIADB_DATA_DIR}:${MARIADB_DATA_DIR}
    env_file:
      - ${LOCAL_ENV_FILE}
    environment:
      MYSQL_ALLOW_EMPTY_PASSWORD: ${MYSQL_ALLOW_EMPTY_PASSWORD}
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
networks: 
  default: 
    name: phpdev

container 2:

services:
  httpd:
    image: "php:7.4-apache"
    restart: 'no'
    ports:
      - '${LOCAL_HTTP_PORT}:80'
    volumes:
      - ${LOCAL_DOCUMENT_ROOT}:/var/www
    build:
      context: .
      dockerfile: ./Dockerfile
networks: 
  default: 
    name: phpdev

The first container you spin up will create the network; the second will attach to it. Now, both containers are attached to the phpdev network, and the PHP/Apache container can make requests to the MariaDB container. Specifically, while creating a Database Connection:

// use the container service name as the host
$dbh = new PDO('mysql:host=mariadb;dbname=mydb', 'username', 'mypass');

Took a while to figure this out, but it works nicely.