1 | initial version |
There are different approaches to connect two Docker containers, but one common solution is to use Docker Compose, which is a tool for defining and running multi-container Docker applications. Here are the basic steps to connect a Django Docker container with another Docker container:
Create a Dockerfile for the second container, based on the image that you want to use, and specify the necessary configurations and dependencies for your application. For example, if you want to use a Postgres database, you can use the official Postgres image and set the environment variables for the database name, user, password, and port.
Create a docker-compose.yml file in the same directory as your Dockerfile(s) and define the services that you want to run. In this case, you need to define two services: one for the Django container and one for the database container. You can set the environment variables, volumes, and ports for each service, and use the "links" option to connect the containers. For example:
version: "3.9"
services:
django:
build:
context: .
dockerfile: Dockerfile
environment:
- DB_HOST=db
- DB_NAME=mydatabase
- DB_USER=mydatabaseuser
- DB_PASSWORD=mypassword
volumes:
- .:/code
ports:
- "8000:8000"
links:
- db
db:
image: postgres
environment:
- POSTGRES_DB=mydatabase
- POSTGRES_USER=mydatabaseuser
- POSTGRES_PASSWORD=mypassword
volumes:
- db-data:/var/lib/postgresql/data/
volumes:
db-data:
This file defines two services: "django" and "db", which run the Dockerfile and the Postgres image, respectively. The "django" service sets the environment variables for the database connection and links to the "db" service. The "db" service sets the environment variables for the database configuration, and creates a named volume for the database data.
$ docker-compose up -d
Creating network "myapp_default" with the default driver
Creating myapp_db_1 ... done
Creating myapp_django_1 ... done
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASSWORD'),
'HOST': os.environ.get('DB_HOST'),
'PORT': '5432',
}
}
This code reads the environment variables for the database connection and sets them as the values for the Django database settings. You can also use the "docker exec" command to access the containers and test the connection manually.
$ docker exec -it myapp_django_1 bash
root@django_container:/code# python manage.py shell
>>> from django.db import connection
>>> c = connection.cursor()
>>> c.execute("SELECT COUNT(*) from myapp_mymodel")
>>> print(c.fetchone())
(42,)
>>> exit()
root@django_container:/code# exit