Deploying a Django Application with MySQL Using Docker Compose
Packing Django App and MySQL within One Docker Compose File
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It provides a range of functionalities to ease web development, such as an ORM, an admin panel, and security features.
MySQL is a popular open-source relational database management system. It is known for its reliability, performance, and ease of use.
Docker is a platform that enables developers to package applications into containers—standardized executable components that combine application source code with the OS libraries and dependencies required to run that code in any environment.
Docker Compose is a tool for defining and running multi-container Docker applications. With a single docker-compose.yml
file, you can deploy an entire stack including databases, web servers, and application code.
This tutorial will guide you through the process of packing a Django application and MySQL database into a single Docker Compose file.
Setting Up the Project
Step 1: Create the Django Project
Create a Django App:
python manage.py startapp myapp
Start a New Django Project:
django-admin startproject myproject
cd myproject
Install Django:
pip install django
Step 2: Prepare the Django Project for Docker
Update ALLOWED_HOSTS
in settings.py
:
ALLOWED_HOSTS = ['*']
Add MySQL Configuration in settings.py
:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'root',
'PASSWORD': 'password',
'HOST': 'db',
'PORT': '3306',
}
}
Create a requirements.txt
File:
Django==4.0
mysqlclient
Step 3: Create Docker-Related Files
Create a docker-compose.yml
File:
version: '3'
services:
db:
image: mysql:5.7
restart: always
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: mydatabase
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
web:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- db
volumes:
mysql_data:
Create a Dockerfile
for Django:
# Use the official Python image.
FROM python:3.9
# Set the working directory.
WORKDIR /app
# Copy the current directory contents into the container at /app.
COPY . /app/
# Install any needed packages specified in requirements.txt.
RUN pip install --no-cache-dir -r requirements.txt
# Make port 8000 available to the world outside this container.
EXPOSE 8000
# Run the application.
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
Step 4: Running the Application
Access the Application:
Open your browser and navigate to http://localhost:8000
.
Apply Migrations:
In another terminal, run:
docker-compose exec web python manage.py migrate
Build and Start the Docker Containers:
docker-compose up --build
This setup ensures that your Django application and MySQL database are both containerized and can be deployed effortlessly in any environment, maintaining consistency and reducing potential errors.