DB Docker Persistence
How to execute Django in Docker with DB persistence
Docker is a platform that allows developers to package and distribute applications with their dependencies into portable containers. Docker offers a powerful solution to simplify the development and deployment process.
In this tutorial, we'll show you how to leverage Docker to execute your Django application with database persistence. By the end, you'll be equipped with the knowledge and tools to efficiently develop and deploy your Django projects using Docker.
β Prerequisitesβ
Before we begin, make sure you have Docker
and Docker Compose
installed on your system.
Docker allows us to containerize our Django application, while Docker Compose helps manage multiple containers and their configurations.
If you haven't installed Docker yet, you can find detailed installation instructions for your operating system on the official Docker website.
β Set up a Django projectβ
Coding Sample: https://github.com/app-generator/sample-django-docker-db-persistence
For this tutorial we will use the project provided above. If git
isn't installed, run following command to install it.
sudo apt-get install git
Then clone the project by running this command.
git clone https://github.com/app-generator/sample-django-docker-db-persistence
β Set up the Dockerfileβ
To containerize your Django application, you'll need a Dockerfileβa configuration file that defines the image's specifications. Our Dockerfile sets up a Python runtime environment, installs project dependencies, copies the code into the container, and configures the necessary port exposure.
This ensures seamless execution of your Django application within a Docker container. Follow these steps:
Open your Django project and search a file called
Dockerfile
in your project's root directory.If the
Dockerfile
doesn't exist, create one and add the following content, then save it.
FROM python:3.9
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
WORKDIR /app
COPY requirements.txt .
# install python dependencies
RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
β Set up the Docker Composeβ
Docker Compose simplifies the management of multiple containers and their dependencies.
In this step, we'll create a docker-compose.yml
file to configure our Django application and the database.
This will ensure that our database data persists even if the container is restarted.
Open
docker-compose.yml
file in your project's root directory.If it doesn't exist, create one and add the following content.
version: '3.8'
services:
appseed-app:
container_name: appseed_app
restart: always
build: .
networks:
- db_network
- web_network
command: >
sh -c "python manage.py makemigrations &&
python manage.py migrate &&
gunicorn --config gunicorn-cfg.py core.wsgi"
nginx:
container_name: nginx
restart: always
image: "nginx:latest"
ports:
- "5085:5085"
volumes:
- ./nginx:/etc/nginx/conf.d
networks:
- web_network
depends_on:
- appseed-app
networks:
db_network:
driver: bridge
web_network:
driver: bridge
Copy and paste the following content into the file.
For PostgreSQL
services:
...
db:
image: postgres
environment:
POSTGRES_DB: ${DB_NAME}
POSTGRES_USER: ${DB_USERNAME}
POSTGRES_PASSWORD: ${DB_PASS}
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- db_network
...
volumes:
postgres_data:For MySQL
services:
...
db:
image: mysql
environment:
MYSQL_DATABASE: ${DB_NAME}
MYSQL_USER: ${DB_USERNAME}
MYSQL_PASSWORD: ${DB_PASS}
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASS}
volumes:
- mysql_data:/var/lib/mysql
networks:
- db_network
...
volumes:
mysql_data:For SQLite
You need to add volume in the
appseed-app
service. The SQLite database will be stored as a file within the container.services:
appseed-app:
container_name: appseed_app
restart: always
build: .
volumes: # add these
- ./data:/app/data # lines
networks:
- db_network
- web_network
Save the file. The complete
docker-compose.yml
file if you use PostgreSQL will look like this.version: '3.8'
services:
db:
image: postgres
environment:
POSTGRES_DB: ${DB_NAME}
POSTGRES_USER: ${DB_USERNAME}
POSTGRES_PASSWORD: ${DB_PASS}
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- db_network
appseed-app:
container_name: appseed_app
restart: always
build: .
networks:
- db_network
- web_network
command: >
sh -c "python manage.py makemigrations &&
python manage.py migrate &&
gunicorn --config gunicorn-cfg.py core.wsgi"
nginx:
container_name: nginx
restart: always
image: "nginx:latest"
ports:
- "5085:5085"
volumes:
- ./nginx:/etc/nginx/conf.d
networks:
- web_network
depends_on:
- appseed-app
networks:
db_network:
driver: bridge
web_network:
driver: bridge
volumes:
postgres_data:
β Configure Django settingsβ
To establish a connection between Django and the database container, we need to modify the environment variable.
Copy the
env.sample
file to.env
.cp env.sample .env
If you are using SQLite as your database, you can skip the next step. Leave the database configuration commented out.
Open
.env
file using a text editor.Remove comment from database variables and fill it by following your database configuration.
For PostgreSQL:
DB_ENGINE=postgresql
DB_HOST=db
DB_NAME=your_db_name
DB_USERNAME=user_name
DB_PASS=your_password
DB_PORT=5432For MySQL:
DB_ENGINE=mysql
DB_HOST=db
DB_NAME=your_db_name
DB_USERNAME=user_name
DB_PASS=your_password
DB_ROOT_PASS=your_root_password
DB_PORT=3306
Fill out the other variables as needed, then save the file.
Open
requirements.txt
file using a text editor.Uncomment the package following the database you used by deleting the
#
in front of it.psycopg2-binary
: for PostgreSQLmysqlclient
: for MySQL
SQLite Settingsβ
If you are using SQLite as your database, you need to update your project settings by following these steps:
Open the
core/settings.py
file in your project.Search for the database config and replace with this following code.
if DB_ENGINE and DB_NAME and DB_USERNAME:
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.' + DB_ENGINE,
'NAME' : DB_NAME,
'USER' : DB_USERNAME,
'PASSWORD': DB_PASS,
'HOST' : DB_HOST,
'PORT' : DB_PORT,
},
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'data', 'db.sqlite3'), # <-- NEW
}
}
Replace the line 'NAME': os.path.join(BASE_DIR, 'db.sqlite3')
with 'NAME': os.path.join(BASE_DIR, 'data', 'db.sqlite3')
.
This ensures that the SQLite database file will be stored in a folder named data
with the filename db.sqlite3
.
β Build and run the containersβ
We'll build and run our Docker containers using the Docker Compose file we created.
This will start the Django development server and connect it to the PostgreSQL
database container.
In your terminal, navigate to your project's root directory.
cd ~/your/django/project
Run the following command to build and start the containers.
docker-compose up --build
Docker Compose will create and configure the containers based on the specifications in the Compose file.
β Visit the app in Browserβ
Once the containers are running, open your web browser and visit http://localhost:5085. You should see your Django application running. However, if this is your first time running the application, you'll need to create a superuser to log in and access the admin interface.
Here's a step-by-step
guide to creating a superuser inside Docker:
Open a terminal and enter your Django container by running the following command:
docker exec -it appseed_app bash
Once inside the container's shell, run the following command.
python manage.py createsuperuser
After providing the necessary details, the superuser will be created successfully. You can now use these credentials to log in to your Django application and access the admin interface
β Resourcesβ
- π Access AppSeed for more starters and support
- π Deploy Projects on Aws, Azure and DO via DeployPRO
- π Create landing pages with Simpllo, an open-source site builder
- π Build apps with Django App Generator (free service)