Skip to main content

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.

Docker DB Persistence - How to implement for a Django Project

βœ… 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:

  1. Open your Django project and search a file called Dockerfile in your project's root directory.

  2. 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.

  1. Open docker-compose.yml file in your project's root directory.

  2. 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
  1. 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
  2. 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.

  1. Copy the env.sample file to .env.

    cp env.sample .env
  2. If you are using SQLite as your database, you can skip the next step. Leave the database configuration commented out.

  3. Open .env file using a text editor.

  4. 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=5432
    • For 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
  5. Fill out the other variables as needed, then save the file.

  6. Open requirements.txt file using a text editor.

  7. Uncomment the package following the database you used by deleting the # in front of it.

    • psycopg2-binary: for PostgreSQL
    • mysqlclient: for MySQL

SQLite Settings​

If you are using SQLite as your database, you need to update your project settings by following these steps:

  1. Open the core/settings.py file in your project.

  2. 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.

  1. In your terminal, navigate to your project's root directory.

    cd ~/your/django/project
  2. Run the following command to build and start the containers.

    docker-compose up --build
  3. 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:

  1. Open a terminal and enter your Django container by running the following command:

    docker exec -it appseed_app bash
  2. 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​