Docker搭建Python+Django+mysql开发环境

参考地址http://blog.csdn.net/yhcvb/article/details/45696961
使用Dockerfile构建镜像,以下出现的achievements为工程的名称

一、使用python2,创建新项目
1.登录服务器,在root下创建文件夹作为项目根目录

mkdir site && cd site
mkdir db achievements

2.创建配置文件Dockerfile

vi Dockerfile
FROM python:2.7
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
RUN mkdir /code/db
WORKDIR /code
ADD ./requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code/

3.创建docker-compose.yml文件

vi docker-compose.yml
db:
  image: mysql
  expose:
    - "3306"
  volumes:
    - ./db:/var/lib/mysql
  environment:
    - MYSQL_DATABASE=achievements
    - MYSQL_ROOT_PASSWORD=root

web:
  build: .
  command: python ./achievements/manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8081:8000"
  links:
    - db

4.创建requirements.txt文件

vi requirements.txt
django==1.7.5
MySQL-python

5.编译构建镜像

docker-compose build

至此,python开发环境搭建完成

6.创建工程

docker-compose run web django-admin.py startproject achievements ./achievements

修改目录的权限

chmod -R 777 achievements/

7.修改工程配置文件setttings.py的数据库配置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'achievements',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'db',
        'PORT': 3306,
    }
}

8.运行

docker-compose up
//在后台运行
docker-compose up -d

访问http://127.0.0.1:8081/

//远程访问不成功可能有防火墙,使用docker命令访问测试
curl http://127.0.0.1:8081/ 

二、使用python3,导入已创建的项目

使用工具SecureCRT可以将文件从本地传到远程服务器
SecureCRT下载和激活地址https://www.cnblogs.com/lianghe01/p/6618651.html

步骤同上,只是文件内容不一样

mkdir site && cd site
mkdir db Achievements
目录结构(Achievements为代码库):
Achievements  db  docker-compose.yml  Dockerfile requirements.txt
vi Dockerfile
FROM python:3.5
ENV PYTHONUNBUFFERED 1
RUN echo python -V
RUN mkdir /code
RUN mkdir /code/db
WORKDIR /code
#ADD ./requirements.txt /code/
RUN pip install -i https://pypi.douban.com/simple django
RUN pip3 install PyMySQL
RUN pip3 install mysqlclient
#RUN pip3 install -r requirements.txt
ADD . /code/
vi docker-compose.yml
db:
  image: mysql
  expose:
    - "3306"
  volumes:
    - ./db:/var/lib/mysql
  environment:
    - MYSQL_DATABASE=achievements
    - MYSQL_ROOT_PASSWORD=root

achievements:
  build: .
  command: python3 ./Achievements/manage.py runserver 0.0.0.0:8000
  volumes:
    - .:/code
  ports:
    - "8000:8000"
  links:
    - db
vi requirements.txt 
django
mysqlclient
#pymysql
docker-compose build
docker-compose up
后台运行
docker-compose up -d
//运行python shell
docker-compose run web mysite/manage.py shell

setting.py文件修改:

ALLOWED_HOSTS = ['*',]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'achievements',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'db',
        'PORT': 3306,
    }
}

制作mysql镜像:https://www.cnblogs.com/weifeng1463/p/7941625.html

你可能感兴趣的:(python,docker)