How to dockerize your django application with mysql, redis and memcached?
In this story, I will try to explain how to dockerize an enter django application. First of all, install docker and docker compose.
Now we will maintain one Dockerfile for our application and another docker-compose.yml file for controlling the docker instances(mysql, redis, memcached). Our directory structure will be :
base_directory
- Dockerfile
- docker-compose.yml
- app
- requirements.txt
Dockerfile:
This file will be used to install different dependencies of the django app, copy the local app directory to the docker instance.
FROM python:3.5
ENV PYTHONUNBUFFERED 1
RUN mkdir /base_directory
WORKDIR /base_directory
ADD . /base_directory/
RUN apt-get update
RUN apt-get install -y git
RUN git init
RUN apt-get install -y gcc python3-dev
RUN apt-get install -y libxml2-dev libxslt1-dev build-essential python3-lxml zlib1g-dev
RUN apt-get install -y default-mysql-client default-libmysqlclient-dev
RUN wget https://bootstrap.pypa.io/get-pip.py
RUN python3 get-pip.py
RUN rm get-pip.py
RUN pip install -r requirements.txt
docker-compose.yml:
This file will be used to download images and after downloading it will create some containers and run the containers.
version: '2'
services:
db:
container_name: 'db'
image: mysql:5.7
ports:
- '3307:3306'
environment:
MYSQL_DATABASE: 'appdb'
MYSQL_PASSWORD: 'root'
MYSQL_ROOT_PASSWORD: 'root'
volumes:
- 'db:/var/lib/mysql'
command: ['mysqld', '--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci'] redis:
container_name: 'redis'
image: 'redis:3.2.0'
ports:
- '6378:6379'
volumes:
- 'redisdata:/data' memcached:
container_name: 'memcached'
image: 'memcached:latest'
ports:
- "11212:11211" web:
build: .
command: python3 app/manage.py runserver 0.0.0.0:8001
volumes:
- '.:/base_directory'
ports:
- "8001:8001"
depends_on:
- db
- redis
- memcached
volumes:
redisdata:
db:
.:
Dockerfile is being run from this docker-compose by the build command under web container. In our settings file, our database settings part will be:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'appdb',
'HOST': 'db',
'PORT': 3306,
'USER': 'root',
'PASSWORD': 'pass',
'OPTIONS': {'sql_mode': 'STRICT_ALL_TABLES', 'charset': 'utf8mb4',},
}
}
We will up the containers by using:
docker-compose up
We can run them in background:
docker-compose up -d
We can make the containers down by:
docker-compose down
We can remove everything from docker volume:
docker-compose down -v
We can access terminal of any container by:
docker exec -it container_name/id /bin/bash
We can import mysql db by:
docker exec -i container mysql -uuser -ppass db <db.sql
If we want to run db first and wait until it becomes fully ready, in that case will first run the db:
docker-compose up db
Then up the others:
docker-compose up
Finally our application will be started on the 8001 port:
http://localhost:8001/