从零开始学习docker(一)

本节将从零开始搭建一个docker镜像,并且运行container。

首先现在本机上搭建一个python flask,新建app.py 内容如下:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
	return "hello docker"
if __name__ == '__main__':
	app.run()

运行环境是python 2.7

iie4bu@hostdocker:~/ddy/docker-flask$ python app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

访问:

iie4bu@hostdocker:~/ddy/docker-flask$ curl -XGET http://127.0.0.1:5000/
hello docker

成功访问!

我们要将这段python程序打包到一个docker镜像中去。新建目录docker-flask,在这个目录中新建Dockerfile,内容如下:

FROM python:2.7 #FROM 表示他的基本的运行环境是python2.7
LABEL maintainer="vincent" #LABEL 表示这个作者是谁
RUN pip install flask #添加他的依赖环境
COPY app.py /app/ #将本地的一个文件拷贝到根目录下app文件夹下面,如果没有这个文件夹会自动创建
WORKDIR /app #设置当前工作目录是/app
EXPOSE 5000 # 暴露5000端口
CMD ["python" ,"app.py"] #运行python app.py程序,

构建镜像:

iie4bu@hostdocker:~/ddy/docker-flask$ docker build -t vincent/flask-hello-world .
Sending build context to Docker daemon  3.072kB
Step 1/7 : FROM python:2.7
 ---> 37093962fbf5
Step 2/7 : LABEL maintainer="vincent"
 ---> Using cache
 ---> 627d5ec958ce
Step 3/7 : RUN pip install flask
 ---> Using cache
 ---> d43f86c119ac
Step 4/7 : COPY app.py /app/
 ---> 4a82cbc4c3ab
Step 5/7 : WORKDIR /app
Removing intermediate container 0cdeca4a4933
 ---> 93259de7edce
Step 6/7 : EXPOSE 5000
 ---> Running in 277dec055ba3
Removing intermediate container 277dec055ba3
 ---> a6c65810538e
Step 7/7 : CMD ["python" ,"app.py"]
 ---> Running in 89fa40f016b6
Removing intermediate container 89fa40f016b6
 ---> fb540978df9e
Successfully built fb540978df9e
Successfully tagged vincent/flask-hello-world:latest

查看镜像:

iie4bu@hostdocker:~/ddy/docker-flask$ docker image ls
REPOSITORY                                      TAG                 IMAGE ID            CREATED             SIZE
vincent/flask-hello-world                       latest              fb540978df9e        41 seconds ago      919MB

如果在构建的过程中有问题,可以利用中间过程产生的镜像ID进行DEBUG。命令docker run -it imageId /bin/bash

运行这个镜像:

iie4bu@hostdocker:~/ddy/docker-flask$ docker run -d vincent/flask-hello-world
d695fbafdd6e99c19849ecc96420ebe6e771207a5382a7189354f64ca7ebaa58

-d:表示后台运行container。

iie4bu@hostdocker:~/ddy/docker-flask$ docker container ls
CONTAINER ID        IMAGE                       COMMAND             CREATED             STATUS              PORTS               NAMES
d695fbafdd6e        vincent/flask-hello-world   "python app.py"     28 seconds ago      Up 26 seconds       5000/tcp            nervous_shaw

目前还无法访问。

转载于:https://my.oschina.net/duanvincent/blog/3066714

你可能感兴趣的:(从零开始学习docker(一))