Docker搭建Django3环境


1. 环境

系统:centos7

2. 前提

  1. 已安装docker
  2. centos7开放对8000端口访问 docker run -p时会自动在iptables中开放相应的端口
  3. centos7内核开启IP转发
     sudo echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
     sudo sysctl -p
     sudo systemctl restart docker
    

3. 使用Dockerfile制作镜像

3.1. 文件目录结构

/home/user/build/
    requirements.txt
    Dockerfile

3.2. requirements.txt文件

需要装的python包

django==3.0.2

3.3. 编写Dockerfile

参考Docker Hub官方python

FROM python:3.6.4-alpine
WORKDIR /root
COPY requirements.txt ./
RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt

备注:alpine版本镜像较小所以使用该版本

3.4. build

cd /home/user/build/
docker build -t py3_django3:v1 .

4. 启动镜像到容器

4.1. django项目文件目录

项目为django官方项目polls

/home/user/django_projects/
    mysite/
        manage.py
        db.sqlite3
        mysite/
            __init__.py
            settings.py
            urls.py
            asgi.py
            wsgi.py
        polls/
            __init__.py
            admin.py
            apps.py
            migrations/
                __init__.py
                0001_initial.py
            models.py
            static/
                polls/
                    images/
                        background.gif
                    style.css
            templates/
                polls/
                    detail.html
                    index.html
                    results.html
            tests.py
            urls.py
            views.py
        templates/
            admin/
                base_site.html

注意:需要修改settings.py中ALLOWED_HOSTS = ['*']

4.2. 启动

cd /home/user/django_projects/mysite/
docker run --rm -it \
    -p 8000:8000 \
    -v "$PWD":/usr/src/myapp \
    -w /usr/src/myapp \
    py3_django3:v1 \
    python manage.py runserver 0.0.0.0:8000

使用浏览器访问宿主机8000端口

发布了31 篇原创文章 · 获赞 11 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/MrRight17/article/details/104306105