Network Two Containers#

In this lab you’ll create a Docker network that you can use to connect two containers. One of the great things about a Docker network is that names and addresses are handled by Docker. On a non-default network containers can be reached by their name. Until now we’ve let Docker automatically give us a name like church_missives, but now we’ll give containers names that we want to be able to use with the --name argument.

Create a Network#

The Django container needs to reach the Postgres. The Postgres container should not expose any ports to the host, it’s completely hidden from the outside world. Let’s create a Docker network:

$ docker network create mysite

Verify your network is there:

$ docker network list
9850eee009e7   bridge    bridge    local
28e6c097494d   mysite    bridge    local
a99d5edd9623   host      host      local
81a76cda7c70   none      null      local

Start Postgress#

If you already have a Postgres container running, stop and remove it. We need to launch it again with the --network option to use the mysite network.

$ docker run -d --rm \
    -v $HOME/data:/var/lib/postgresql/data \
    -e POSTGRES_PASSWORD=django -e POSTGRES_DB=mysite \
    --network mysite \
    --name postgres \


Notice that port forwarding has been disabled.

Update Django’s Configuration#

With Postgres started in a container named postgres you can update Django’s

    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mysite',
        'USER': 'postgres',
        'PASSWORD': 'django',
        'HOST': 'postgres',

Rebuild and run your container on the mysite network:

$ docker run -it --rm -p 8000:8000 \
    --network mysite --name django \
    -e SECRET_KEY=mysecretkey -e PORT=8000 \


We still need a port forward so our app is visible to the outside.

Clean Up#

With your data safe, you’re free to remove the containers any time you want. Stop and remove your two running containers:

$ docker stop django postgres