使用docker-compose+nginx+django部署项目

使用docker-compose+nginx+django部署项目

1 centos上下载docker + docker-compose

2 基础目录

image-20210622180353530

3 创建python+django+uwsgi的镜像

​ 创建python+django+uwsgi的纯净镜像,命名镜像名为django:

1
2
3
4
5
6
FROM python:3.6.2
RUN mkdir /code
ADD ./requirements.txt /code
WORKDIR /code
RUN pip3 install -r requirements.txt
RUN rm -f requirements.txt

4 基础目录中的Dockerfile

1
2
3
4
5
6
FROM django
WORKDIR /code
RUN mkdir bbs_practice2 #创建项目目录cat
ADD . /code/bbs_practice2
WORKDIR /code/bbs_practice2
RUN python manage.py collectstatic

5 创建uwsgi配置文件

​ 创建conf/uwsgi.ini配置文件

1
2
3
4
5
6
[uwsgi]
socket=0.0.0.0:8000
chdir=/code/bbs_practice2
module=bbs_practice2.wsgi
master=True
processes=4

6 静态资源配置

1
2
3
4
5
STATIC_URL = '/bootstrap&jquery/'
STATICFILES_DIRS = [
'bootstrap&jquery'
]
STATIC_ROOT=STATos.path.join(BASE_DIR,'dist')

7 创建nginx配置文件

​ 创建nginx/nginc.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
server {
listen 80;
charset utf-8;
location / {
include uwsgi_params;
uwsgi_pass 10.127.2.10:8000;
}
location /static {
autoindex on;
alias /code/bbs_practice2/dist;
}
}
}

8 创建nginx的Dockerfile

创建nginx/Dockerfile

1
2
3
4
5
6
7
8
#nginx/Dockerfile
FROM nginx

WORKDIR /etc/nginx/
RUN cp nginx.conf ./nginx.conf.bak
COPY nginx.conf ./

CMD ["nginx", "-g", "daemon off;"]

9 数据库连接配置

1
2
3
4
5
6
7
8
9
10
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'bbs_practice2',
'HOST': '10.127.2.1',#连接本机linux的mysql
'PORT': 3306,
'USER': 'root',
'PASSWORD': '123456'
}
}

10 创建docker-compose.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
version: '3'

services:
web:
build: .
volumes:
- bootstrap&jquery:/code/bbs_practice2 #代码目录映射
privileged: true
networks:
net-django:
ipv4_address: 10.127.2.10
command: uwsgi --ini /code/bbs_practice2/conf/uwsgi.ini #注意:在这里的路径是容器内的项目所在的路径,而不是宿主机放项目的路径

nginx:
container_name: nginx-container
restart: always
depends_on:
- web
links:
- "web:web"
build: ./nginx
volumes:
- bootstrap&jquery:/code/bbs_practice2 #代码目录映射
ports:
- 8080:80
networks:
net-django:
ipv4_address: 10.127.2.2

networks:
net-django:
ipam:
config:
- subnet: 10.127.2.0/24 #自定义的网段
volumes:
static:

11 创建容器并启动

1
2
docker-compose build
docker-compose up -d