DevOps Engineering Containers05 / 21

SECTION 03 · 30 MIN READ & EXPLORE

Container Networking

Connect MySQL and phpMyAdmin by service name on a custom Docker bridge network.

How Does Container Networking Work?

Every container runs in its own network namespace with a private loopback interface (127.0.0.1) and IP address. Attaching containers to the same user-defined bridge network gives them automatic internal DNS resolution by container name, while port publishing (-p) exposes selected container ports to your host machine.

EXPLORE THE DIAGRAM

Container networking: host ports and bridge DNS

Experiment freely. Changes disappear when you reset or refresh.

Preview of Container networking: host ports and bridge DNS

Why and When to Use Container Networks?

Use custom bridge networks whenever multiple containers need to communicate cleanly by name without hardcoding IP addresses or exposing internal services publicly.

SCENARIOS

Connecting MySQL and phpMyAdmin

Create a Bridge Network & Start MySQL

network create--network-p-e
SITUATION

You need an isolated development database that other containers can reach by name while your host workstation can still connect on localhost:3306.

TASK

Create a custom bridge network named can-network and launch a MySQL 8.0 container attached to it.

# 1. Create a user-defined bridge network
docker network create can-network

# 2. Start MySQL attached to can-network (ephemeral instance for this exercise)
docker run -d \
  --name mysql-dev \
  --network can-network \
  -p 127.0.0.1:3306:3306 \
  -e MYSQL_ROOT_PASSWORD=root \
  -e MYSQL_DATABASE=can2025 \
  mysql:8.0

# 3. Check logs until MySQL reports it is ready for connections
docker logs mysql-dev

WHAT TO OBSERVE

docker network ls lists can-network, and docker logs mysql-dev ends with MySQL ready for connections on port 3306.

Connect phpMyAdmin by Container Name

--network-p-e PMA_HOST
SITUATION

phpMyAdmin needs to connect to MySQL. Inside phpMyAdmin, localhost points to phpMyAdmin itself—not to the database container.

TASK

Attach phpMyAdmin to the same network, pass PMA_HOST=mysql-dev so Docker DNS resolves the database, and open the web UI.

# Start phpMyAdmin on can-network pointing to mysql-dev by container name
docker run -d \
  --name pma \
  --network can-network \
  -p 127.0.0.1:8080:80 \
  -e PMA_HOST=mysql-dev \
  phpmyadmin

Open http://localhost:8080 in your browser and sign in with username root and password root.

WHAT TO OBSERVE

phpMyAdmin connects to mysql-dev over can-network and displays the empty can2025 database.

Seed the Database from the Host

127.0.0.1:3306rm -fnetwork rm
SITUATION

A Python script running on your host workstation needs to populate tables inside the containerized MySQL instance.

TASK

Run the seed script against localhost:3306, verify the rows in phpMyAdmin, then remove the containers and network.

# 1. Run the Python seed script from inside the 01-containers directory
uv run --with mysql-connector-python seed_can_2025.py

# 2. Refresh phpMyAdmin to verify the squad table and rows

# 3. Tear down the containers and custom network when finished
docker rm -f mysql-dev pma
docker network rm can-network

WHAT TO OBSERVE

The script connects through the published host port 127.0.0.1:3306 and inserts the Morocco CAN 2025 squad, visible immediately inside phpMyAdmin.

Explore the files

seed_can_2025.py

import mysql.connector
import time

def get_connection():
    # Retry connection logic since container might take a moment to start
    retries = 5
    while retries > 0:
        try:
            conn = mysql.connector.connect(
                host="127.0.0.1",
                user="root",
                password="root",
                database="can2025"
            )
            return conn
        except mysql.connector.Error as err:
            print(f"Connection failed: {err}. Retrying in 2s...")
            time.sleep(2)
            retries -= 1
    return None

def seed_data():
    conn = get_connection()
    if not conn:
        print("❌ Could not connect to database. Did you expose port 3306?")
        return

    cursor = conn.cursor()

    # Create table
    cursor.execute("""
    CREATE TABLE IF NOT EXISTS morocco_can_2025 (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        position VARCHAR(50),
        club VARCHAR(100)
    )
    """)
    print("✅ Table 'morocco_can_2025' created.")

    # Data
    players = [
        ("Yassine Bounou", "Goalkeeper", "Al-Hilal"),
        ("Achraf Hakimi", "Defender", "PSG"),
        ("Nayef Aguerd", "Defender", "Marseille"),
        ("Romain Saiss", "Defender", "Al-Shabab"),
        ("Noussair Mazraoui", "Defender", "Man United"),
        ("Sofyan Amrabat", "Midfielder", "Real Betis"),
        ("Azzedine Ounahi", "Midfielder", "Girona"),
        ("Youssef En-Nesyri", "Forward", "Fenerbace"),
        ("Brahim Diaz", "Midfielder", "Real Madrid")
    ]

    # Insert
    cursor.executemany("""
    INSERT INTO morocco_can_2025 (name, position, club)
    VALUES (%s, %s, %s)
    """, players)
    
    conn.commit()
    print(f"✅ Inserted {cursor.rowcount} players into the database.")

    cursor.close()
    conn.close()

if __name__ == "__main__":
    seed_data()

Quick Reference

CHEAT SHEET

Docker networking commands & drivers

Essential commands for creating isolated bridge networks, resolving services by name, and publishing ports.

Network Lifecycle (CRUD)

docker network create
Create a custom bridge network with DNS
CREATE
docker network ls
List all Docker networks
READ
docker network inspect
View subnets, gateways, and attached containers
READ
docker network rm
Remove an unused Docker network
DELETE

Connecting & Publishing

--network NAME
Attach a container to a network at startup
FLAG
-p 127.0.0.1:H:C
Publish container port C to host port H locally
FLAG
docker network connect
Attach a running container to a network
UPDATE
docker logs NAME
Inspect service startup and readiness logs
DEBUG

Common Network Drivers

bridge
Isolated virtual network on a single host (default for custom networks)
DRIVER
host
Shares the host network namespace directly (no port isolation)
DRIVER
none
Disables all networking except loopback inside the container
DRIVER
container:NAME
Shares another container's network stack and localhost
MODE
A LITTLE CLEARER?

Take a moment to explain the idea in your own words.

Progress is saved in this browser.

DevOps Engineering

Course overview ↗

01Introduction to DevOps

  1. What is DevOps?20m
  2. DevOps Roles20m