创建一个最最简单的python+django项目,然后在docker容器中运行。
环境:
192.168.174.134服务器中
docker镜像: python:2(python2.7.15)
django: 1.8.3
1. 在134服务器中创建python项目
django-admin startproject ops
python manage.py migrate
创建一个root用户
python manage.py createsuperuser
root@ubuntu:~/ops# pwd
/root/ops
root@ubuntu:~/ops# ls
db.sqlite3 manage.py ops
root@ubuntu:~/ops# ls ops
__init__.py __init__.pyc settings.py settings.pyc urls.py urls.pyc wsgi.py wsgi.pyc
运行验证:python manage.py runserver 0.0.0.0:8888
访问python admin,验证服务ok
http://192.168.174.134:8888/admin/
2. docker pull python:2将镜像pull下来
root@ubuntu:~/ops# docker images | grep python
python 2 6f0ab4c651e7 4 days ago 907.7 MB
3. 编写Dockerfile
root@ubuntu:~/docker/dockerfile# ls
Django-1.8.3.tar.gz Dockerfile Dockerfile.bak ops ops.tar.gz
root@ubuntu:~/docker/dockerfile# cat Dockerfile
FROM python:2
ADD Django-1.8.3.tar.gz /usr/local/src
WORKDIR /usr/local/src/Django-1.8.3
RUN python setup.py install
ADD ops.tar.gz /code
WORKDIR /code/ops
ENV PATH /usr/bin/python:$PATH
EXPOSE 8888
CMD ["/bin/bash", "run.sh"]
其中run.sh
放在了ops项目的目录下,为启动python服务的脚本
root@ubuntu:~/docker/dockerfile/ops# ls
db.sqlite3 manage.py ops run.sh
root@ubuntu:~/docker/dockerfile/ops# cat run.sh
python /code/ops/manage.py runserver 0.0.0.0:8888
root@ubuntu:~/docker/dockerfile/ops# pwd
/root/docker/dockerfile/ops
4. 通过Dockerfile构建镜像
docker build -t ops:v1 .
之前构建过了,构建日志比较简单了
Sending build context to Docker daemon 7.351 MB
Sending build context to Docker daemon
Step 0 : FROM python:2
---> 6f0ab4c651e7
Step 1 : ADD Django-1.8.3.tar.gz /usr/local/src
---> Using cache
---> 3396d9f2fe48
Step 2 : WORKDIR /usr/local/src/Django-1.8.3
---> Using cache
---> 4748eaa68a72
Step 3 : RUN python setup.py install
---> Using cache
---> 2c9ed9c547b2
Step 4 : ADD ops.tar.gz /code
---> Using cache
---> 8a513509c908
Step 5 : WORKDIR /code/ops
---> Using cache
---> b097beb37496
Step 6 : ENV PATH /usr/bin/python:$PATH
---> Using cache
---> 3264fc493457
Step 7 : EXPOSE 8888
---> Using cache
---> c719b6159390
Step 8 : CMD /bin/bash run.sh
---> Using cache
---> 9f1e094d0189
Successfully built 9f1e094d0189
查看镜像:
root@ubuntu:~/docker/dockerfile# docker images | grep ops
ops v1 f3fccc152eaa 11 seconds ago 983.8 MB
5. 创建运行容器
root@ubuntu:~/docker/dockerfile# docker run -d --name ops -p 8888:8888 ops:v1
eeb14a3e7ea034f93a3e9158734e1f63fce85cb267a836b45d410fbd88306c64
查看将容器中的8888端口映射到本机的8888端口
root@ubuntu:~/docker/dockerfile# docker ps -l
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
eeb14a3e7ea0 ops:v1 "/bin/bash run.sh" 35 seconds ago Up 34 seconds 0.0.0.0:8888->8888/tcp ops
root@ubuntu:~/docker/dockerfile# netstat -antp | grep 8888
tcp6 0 0 :::8888 :::* LISTEN 52832/docker-proxy