使用docker构建部署django+mysql项目(docker-compose)

这里需要升级docker版本,因为centos7 yum源默认自带的docker版本无法使用compose,详情见: http://nanguawu.me/container/5013.html

容器部署目录结构:

[root@vm2 web_django]# tree -L 2
.
├── db
│   ├── auto.cnf
│   ├── ca-key.pem
│   ├── ca.pem
│   ├── client-cert.pem
│   ├── client-key.pem
│   ├── data01
│   ├── ib_buffer_pool
│   ├── ibdata1
│   ├── ib_logfile0
│   ├── ib_logfile1
│   ├── mysql
│   ├── performance_schema
│   ├── private_key.pem
│   ├── public_key.pem
│   ├── server-cert.pem
│   ├── server-key.pem
│   └── sys
├── docker-compose.yml
├── Dockerfile
├── manage.py
├── requirements.txt
└── website
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py
6 directories, 21 files

requirements.txt文件内容:

django==1.10.8
MySQL-python

Dockfile文件内容:

FROM python:2.7
MAINTAINER Larryliang "cecnck@gmail.com"
ENV PYTHONUNBUFFERD 1
RUN mkdir /code
RUN mkdir /code/db
RUN mkdir /code/website
WORKDIR /code
ADD requirements.txt /code/
RUN  pip install -r requirements.txt -i https://pypi.douban.com/simple   --trusted-host pypi.douban.com
ADD . /code/

docker-compose.yml文件内容:

version: '3'
services:
  db:
    image: mysql
    expose: 
      - "3306"
    volumes:
      - ./db:/var/lib/mysql
    environment:
      - MYSQL_DATABASE=data01
      - MYSQL_ROOT_PASSWORD=data01
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

Build项目

[root@vm2 web_django]# docker version
Client:
 Version:      17.07.0-ce
 API version:  1.31
 Go version:   go1.8.3
 Git commit:   8784753
 Built:        Tue Aug 29 17:42:01 2017
 OS/Arch:      linux/amd64
Server:
 Version:      17.07.0-ce
 API version:  1.31 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   8784753
 Built:        Tue Aug 29 17:43:23 2017
 OS/Arch:      linux/amd64
 Experimental: false
[root@vm2 web_django]# docker-compose  build
db uses an image, skipping
Building web
Step 1/10 : FROM python:2.7
 ---> 8a90a66b719a
Step 2/10 : MAINTAINER Larryliang "cecnck@gmail.com"
 ---> Using cache
 ---> 580a124b98a8
Step 3/10 : ENV PYTHONUNBUFFERD 1
 ---> Using cache
 ---> 87f8ce3ca0a2
Step 4/10 : RUN mkdir /code
 ---> Using cache
 ---> 83f26201a74f
Step 5/10 : RUN mkdir /code/db
 ---> Using cache
 ---> 06c6e22dd86a
Step 6/10 : RUN mkdir /code/website
 ---> Using cache
 ---> c0abb5fd2218
Step 7/10 : WORKDIR /code
 ---> Using cache
 ---> 942e3b5a8e20
Step 8/10 : ADD requirements.txt /code/
 ---> Using cache
 ---> 0a4a0bd7b379
Step 9/10 : RUN pip install -r requirements.txt -i https://pypi.douban.com/simple   --trusted-host pypi.douban.com
 ---> Using cache
 ---> 09600fc029fd
Step 10/10 : ADD . /code/
 ---> 11773f943a61
Successfully built 11773f943a61
Successfully tagged webdjango_web:latest

创建项目和APP

[root@vm2 web_django]# docker-compose  run web django-admin.py startproject website  .
Creating network "webdjango_default" with the default driver
Pulling db (mysql:latest)...
latest: Pulling from library/mysql
ad74af05f5a2: Already exists
0639788facc8: Pull complete
de70fa77eb2b: Pull complete
724179e94999: Pull complete
50c77fb16ba6: Pull complete
d51f459239fb: Pull complete
937bbdd4305a: Pull complete
35369f9634e1: Pull complete
f6016aab25f1: Pull complete
5f1901e920da: Pull complete
fdf808213c5b: Pull complete
Digest: sha256:96edf37370df96d2a4ee1715cc5c7820a0ec6286551a927981ed50f0273d9b43
Status: Downloaded newer image for mysql:latest
Creating webdjango_db_1 ... 
Creating webdjango_db_1 ... done

修改配置website/settings.py如下,之后重新build

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

启动容器:

[root@vm2 web_django]# docker-compose  up
Starting webdjango_db_1 ... 
Starting webdjango_db_1 ... done
Recreating webdjango_web_1 ... 
Recreating webdjango_web_1 ... done
Attaching to webdjango_db_1, webdjango_web_1
db_1   | 2017-09-07T12:22:23.513202Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1   | 2017-09-07T12:22:23.515941Z 0 [Note] mysqld (mysqld 5.7.19) starting as process 1 ...
db_1   | 2017-09-07T12:22:23.612191Z 0 [Note] InnoDB: PUNCH HOLE support available
db_1   | 2017-09-07T12:22:23.612240Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db_1   | 2017-09-07T12:22:23.612247Z 0 [Note] InnoDB: Uses event mutexes
db_1   | 2017-09-07T12:22:23.612252Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
db_1   | 2017-09-07T12:22:23.612256Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
db_1   | 2017-09-07T12:22:23.612260Z 0 [Note] InnoDB: Using Linux native AIO
db_1   | 2017-09-07T12:22:23.612510Z 0 [Note] InnoDB: Number of pools: 1
db_1   | 2017-09-07T12:22:23.612640Z 0 [Note] InnoDB: Using CPU crc32 instructions
db_1   | 2017-09-07T12:22:23.699132Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
db_1   | 2017-09-07T12:22:23.706780Z 0 [Note] InnoDB: Completed initialization of buffer pool
db_1   | 2017-09-07T12:22:23.708851Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db_1   | 2017-09-07T12:22:23.721021Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
db_1   | 2017-09-07T12:22:24.210121Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1   | 2017-09-07T12:22:24.210959Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1   | 2017-09-07T12:22:24.884250Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1   | 2017-09-07T12:22:24.937435Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
db_1   | 2017-09-07T12:22:24.937508Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
db_1   | 2017-09-07T12:22:24.938536Z 0 [Note] InnoDB: Waiting for purge to start
db_1   | 2017-09-07T12:22:24.989070Z 0 [Note] InnoDB: 5.7.19 started; log sequence number 12143700
db_1   | 2017-09-07T12:22:24.989543Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1   | 2017-09-07T12:22:24.992481Z 0 [Note] Plugin 'FEDERATED' is disabled.
db_1   | 2017-09-07T12:22:25.148161Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
db_1   | 2017-09-07T12:22:25.186490Z 0 [Warning] CA certificate ca.pem is self signed.
db_1   | 2017-09-07T12:22:25.189451Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
db_1   | 2017-09-07T12:22:25.189543Z 0 [Note] IPv6 is available.
db_1   | 2017-09-07T12:22:25.189564Z 0 [Note]   - '::' resolves to '::';
db_1   | 2017-09-07T12:22:25.189595Z 0 [Note] Server socket created on IP: '::'.
db_1   | 2017-09-07T12:22:25.314065Z 0 [Note] InnoDB: Buffer pool(s) load completed at 170907 12:22:25
db_1   | 2017-09-07T12:22:25.320253Z 0 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
db_1   | 2017-09-07T12:22:25.320383Z 0 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
db_1   | 2017-09-07T12:22:25.320534Z 0 [Warning] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode.
db_1   | 2017-09-07T12:22:25.320580Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
db_1   | 2017-09-07T12:22:25.337153Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
db_1   | 2017-09-07T12:22:25.486920Z 0 [Warning] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode.
db_1   | 2017-09-07T12:22:25.486995Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
db_1   | 2017-09-07T12:22:25.741875Z 0 [Note] Event Scheduler: Loaded 0 events
db_1   | 2017-09-07T12:22:25.742708Z 0 [Note] mysqld: ready for connections.
db_1   | Version: '5.7.19'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
db_1   | 2017-09-07T12:22:25.742789Z 0 [Note] Executing 'SELECT * FROM INFORMATION_SCHEMA.TABLES;' to get a list of tables using the deprecated partition engine. You may use the startup option '--disable-partition-engine-check' to skip this check. 
db_1   | 2017-09-07T12:22:25.742799Z 0 [Note] Beginning of list of non-natively partitioned tables
db_1   | 2017-09-07T12:22:25.877821Z 0 [Note] End of list of non-natively partitioned tables

或者放到后台启动:

[root@vm2 web_django]# docker-compose  up -d
Starting webdjango_db_1 ... 
Starting webdjango_db_1 ... done
Starting webdjango_web_1 ... 
Starting webdjango_web_1 ... done

测试结果:

[root@vm2 web_django]# curl  http://192.168.100.120:8000/ 
<!DOCTYPE html>
<html><head>
  <meta http-equiv="content-type">
  <meta><title>Welcome to Django</title>
  <style>
    html * { padding:0; margin:0; }
    body * { padding:10px 20px; }
    body * * { padding:0; }
    body { font:small sans-serif; }
    body>div { border-bottom:1px solid #ddd; }
    h1 { font-weight:normal; }
    h2 { margin-bottom:.8em; }
    h2 span { font-size:80%; color:#666; font-weight:normal; }
    h3 { margin:1em 0 .5em 0; }
    h4 { margin:0 0 .5em 0; font-weight: normal; }
    table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }
    tbody td, tbody th { vertical-align:top; padding:2px 3px; }
    thead th {
      padding:1px 6px 1px 3px; background:#fefefe; text-align:left;
      font-weight:normal; font-size:11px; border:1px solid #ddd;
    }
    tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; }
    #summary { background: #e0ebff; }
    #summary h2 { font-weight: normal; color: #666; }
    #explanation { background:#eee; }
    #instructions { background:#f6f6f6; }
    #summary table { border:none; background:transparent; }
  </style>
</head>
<body>
<div>
  <h1>It worked!</h1>
  <h2>Congratulations on your first Django-powered page.</h2>
</div>
<div>
  <p>
    Of course, you haven't actually done any work yet. Next, start your first app by running <code>python manage.py startapp [app_label]</code>.
  </p>
</div>
<div>
  <p>
    You're seeing this message because you have <code>DEBUG = True</code> in your Django settings file and you haven't configured any URLs. Get to work!
  </p>
</div>
</body></html>

观察容器状态:

[root@vm2 web_django]# docker ps  
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
2d549e242606        webdjango_web       "python manage.py ..."   7 minutes ago       Up 50 seconds       0.0.0.0:8000->8000/tcp   webdjango_web_1
ce18133de30c        mysql               "docker-entrypoint..."   About an hour ago   Up 51 seconds       3306/tcp                 webdjango_db_1
[root@vm2 web_django]# docker top 2d549e242606  #查看容器中进程
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                20355               20335               0                   08:28               ?                   00:00:00            python manage.py runserver 0.0.0.0:8000
root                20433               20355               1                   08:28               ?                   00:00:05            /usr/local/bin/python manage.py runserver 0.0.0.0:8000
[root@vm2 web_django]# docker exec -it  2d549e242606 df -Th  #容器中执行一条命令并返回
Filesystem          Type     Size  Used Avail Use% Mounted on
overlay             overlay   27G  3.9G   24G  15% /
tmpfs               tmpfs    489M     0  489M   0% /dev
tmpfs               tmpfs    489M     0  489M   0% /sys/fs/cgroup
/dev/mapper/cl-root xfs       27G  3.9G   24G  15% /code
shm                 tmpfs     64M     0   64M   0% /dev/shm
tmpfs               tmpfs    489M     0  489M   0% /sys/firmware
[root@vm2 web_django]# docker diff  2d549e242606  #查看容器变化
C /usr
C /usr/local
C /usr/local/lib
C /usr/local/lib/python2.7
A /usr/local/lib/python2.7/decimal.pyc
A /usr/local/lib/python2.7/UserList.pyc
A /usr/local/lib/python2.7/argparse.pyc
A /usr/local/lib/python2.7/BaseHTTPServer.pyc
C /usr/local/lib/python2.7/wsgiref
A /usr/local/lib/python2.7/wsgiref/__init__.pyc
A /usr/local/lib/python2.7/wsgiref/simple_server.pyc
A /usr/local/lib/python2.7/wsgiref/util.pyc
A /usr/local/lib/python2.7/wsgiref/handlers.pyc
A /usr/local/lib/python2.7/wsgiref/headers.pyc
A /usr/local/lib/python2.7/imghdr.pyc
C /usr/local/lib/python2.7/email
C /usr/local/lib/python2.7/email/mime
A /usr/local/lib/python2.7/email/mime/nonmultipart.pyc
A /usr/local/lib/python2.7/email/mime/message.pyc
A /usr/local/lib/python2.7/email/mime/base.pyc
A /usr/local/lib/python2.7/email/mime/multipart.pyc
A /usr/local/lib/python2.7/email/mime/audio.pyc
A /usr/local/lib/python2.7/email/mime/image.pyc
A /usr/local/lib/python2.7/email/mime/text.pyc
A /usr/local/lib/python2.7/sndhdr.pyc
[root@vm2 web_django]# docker inspect 2d549e242606 
[
    {
        "Id": "2d549e2426067461adc1d635bb5f41db464bf0b8d57fbe57ddd9b5381c67e24e",
        "Created": "2017-09-07T12:22:22.395256812Z",
        "Path": "python",
        "Args": [
            "manage.py",
            "runserver",
            "0.0.0.0:8000"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 20355,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2017-09-07T12:28:57.89394279Z",
            "FinishedAt": "2017-09-07T12:28:52.523766859Z"
        },
        ...
        ...
            "Networks": {
                "webdjango_default": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": [
                        "web",
                        "2d549e242606"
                    ],
                    "NetworkID": "fc66e543785ee4abb611ad6b3319717fb0f6af56fd710358990e0f0309d34b59",
                    "EndpointID": "54ef82cd8b8bcea0abe60e4c9428ab6401839ac1df6972be6da9b75923372994",
                    "Gateway": "172.18.0.1",
                    "IPAddress": "172.18.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:12:00:03",
                    "DriverOpts": null
                }
            }
        }
    }
]

关闭容器:

[root@vm2 web_django]# docker-compose  down 
Stopping webdjango_web_1 ... done
Stopping webdjango_db_1  ... done
Removing webdjango_web_1     ... done
Removing webdjango_web_run_5 ... done
Removing webdjango_web_run_4 ... done
Removing webdjango_web_run_3 ... done
Removing webdjango_web_run_2 ... done
Removing webdjango_web_run_1 ... done
Removing webdjango_db_1      ... done
Removing network webdjango_default

至此django环境搭建测试完毕。

标签:MySQLDocker部署 发布于:2019-11-09 00:52:27