Write down Docker Compose file for Python Django and MySQL Application
Here's a sample Docker Compose file for a Python Django app using a MySQL database:
- Directory Structure:
/mydjangoapp
|-- app
| |-- manage.py
| `-- myapp
| |-- __init__.py
| |-- settings.py
| |-- urls.py
| `-- wsgi.py
|-- docker-compose.yml
|-- Dockerfile
|-- requirements.txt
`-- mysql
`-- init.sql
- Dockerfile:
# Use an official Python runtime as a parent image
FROM python:3.9
# Set environment variables
ENV PYTHONUNBUFFERED 1
ENV DJANGO_HOME /app
# Create and set the working directory
WORKDIR $DJANGO_HOME
# Copy the current directory contents into the container at /app
COPY . $DJANGO_HOME
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Expose port 8000 to the outside world
EXPOSE 8000
# Define the default command to run when the container starts
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
- requirements.txt:
Django==3.2.5
mysqlclient==2.0.3
- mysql/init.sql:
CREATE DATABASE mydatabase;
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON mydatabase.* TO 'myuser'@'%';
FLUSH PRIVILEGES;
- docker-compose.yml:
version: '3'
services:
web:
build: .
ports:
- "8000:8000"
depends_on:
- db
environment:
- DJANGO_DB_HOST=db
- DJANGO_DB_PORT=3306
- DJANGO_DB_NAME=mydatabase
- DJANGO_DB_USER=myuser
- DJANGO_DB_PASSWORD=mypassword
db:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: rootpassword
MYSQL_DATABASE: mydatabase
MYSQL_USER: myuser
MYSQL_PASSWORD: mypassword
ports:
- "3306:3306"
command: --init-file /docker-entrypoint-initdb.d/init.sql
volumes:
- ./mysql/init.sql:/docker-entrypoint-initdb.d/init.sql
In this setup:
The Django application is in the
app
directory, with the Django-related files and therequirements.txt
file.The MySQL initialization script (
init.sql
) sets up a database (mydatabase
) and a user (myuser
) with the specified password.The Docker Compose file (
docker-compose.yml
) defines two services:web
for the Django application anddb
for MySQL. Thedepends_on
option ensures that the Django application waits for the MySQL database to be ready before starting.The
DJANGO_DB_*
environment variables are used to configure the Django application's connection to the MySQL database.
To run the application, navigate to the directory containing the docker-compose.yml
file and execute:
docker-compose up
This builds the Docker image for the Django app, starts the MySQL container, and begins the Django development server. You can access the app at http://localhost:8000
.