Docker for Django

Joey Masip Romeu
Jun 24, 2018 · 4 min read
docker --version

Case 1: I’m creating a Django project from scratch and I want to set up a development environment with Docker.

Step1: Clone the docker-django repository which has the docker configuration files.

git clone https://github.com/joeymasip/docker-django.git

Step2: Create the Django project.

#cd to the location where you cloned the project
cd ~/Development/docker-django
#start the containers
docker-compose up -d
docker ps
docker-compose run django django-admin.py startproject project_name .

Step3: Create the Django application.

docker-compose run django python manage.py startapp app_name
docker-compose up -d
docker ps

Step4: Update settings.

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

'app_name',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'docker_django_db',
'USER': 'dbuser',
'PASSWORD': 'dbpw',
'HOST': 'mysql',
'PORT': '3306',
'TEST': {
'NAME': 'docker_django_db_test',
},
}
}

Step5: Create the User model.

#app_name/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
pass
AUTH_USER_MODEL = 'app_name.User'

Step6: Run migrations.

docker-compose exec django bash
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
http://127.0.0.1:8000/
http://127.0.0.1:8000/admin/

Case 2: I already have a Django project

Step1: Clone the docker-django repository which has the docker configuration files.

git clone https://github.com/joeymasip/docker-django.git

Step2: Move all files to your already created Django project.

Step3: Start the docker images inside your Django project folder.

docker-compose up -d

Step4: Update database settings.

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'docker_django_db',
'USER': 'dbuser',
'PASSWORD': 'dbpw',
'HOST': 'mysql',
'PORT': '3306',
'TEST': {
'NAME': 'docker_django_db_test',
},
}
}

Step5: Run migrations.

docker-compose exec django bash
python manage.py migrate
http://127.0.0.1:8000/
http://127.0.0.1:8000/admin/
http://127.0.0.1:8000/whatever-slug-you-want-from-your-project

Joey Masip Romeu

Written by

Coder, Entrepreneur, Co-founder at SlowCode

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade