When you want to run your Django applications on any machine and start in one click, you may use Docker. This way called as "serverless architecture". Docker allows you to run applications on any computer. It's very convenient and simple.
Complete structure of project:
demo_project/
|
|-- manage.py
|
|-- env/
|
|-- backend/
| |
| |-- asgi.py
| |-- __init__.py
| |-- settings.py
| |-- urls.py
| |-- wsgi.py
|
|-- core/
| |
| |-- admin.py
| |-- apps.py
| |-- __init__.py
| |-- models.py
| |-- tests.py
| |-- views.py
|
|-- Dockerfile
|
|-- docker-compose.yaml
|
|-- nginx/
|
|-- default.conf
1. Create Django application.
2. Create Dockerfile file in project's root folder and with this parameters:
FROM python:latest
ARG APP=/app
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
WORKDIR ${APP}
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "2", "backend.wsgi:application"]
3. Create docker-compose.yaml file in project's root folder and put following values:
services:
database:
container_name: database
image: postgres:latest
restart: unless-stopped
shm_size: 128mb
networks:
- internal_network
volumes:
- /var/lib/postgresql/data/:/var/lib/postgresql/data/
environment:
POSTGRES_HOST: database
POSTGRES_DB: database_name
POSTGRES_USER: database_user
POSTGRES_PASSWORD: password
ports:
- 127.0.0.1:5432:5432
backend:
container_name: backend
build:
context: .
dockerfile: Dockerfile
restart: unless-stopped
depends_on:
- database
networks:
- internal_network
volumes:
- ./media/:/app/media/
ports:
- 127.0.0.1:8000:8000
nginx:
container_name: nginx
image: nginx
restart: unless-stopped
depends_on:
- backend
networks:
- internal_network
volumes:
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
ports:
- '80:80'
- '443:443'
networks:
internal_network:
ipam:
driver: default
config:
- subnet: 172.18.0.0/24
4. Create default.conf file in "nginx" directory:
server {
listen 80 default_server;
server_name _;
location / {
proxy_set_header Host $host;
proxy_pass http://backend:8000;
}
}
5. Now start application:
docker compose up -d