本博客为JDGan自修Docker的笔记,如有粗鄙之处,还请见谅~
Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。容器是完全使用沙箱机制,相互之间不会有任何接口。
——所以简单来说,就是实现数据隔离的一个第三发开源框架。
由于docker采用LXC轻量级虚拟化方案,得以方便快速的构建隔离的标准化运行环境。在docker的网站上提到了docker的典型场景:
Well, I don’t know yet. Let’s get start!!
访问这里去下载docker安装包。
运行docker程序,然后打开命令行(终端),运行docker run hello-world
。然后应该可以看到以下日志:
$ docker run hello-world
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
...(snipped)...
检查docker版本号docker --version
。
$ docker --version
Docker version 17.06.0-ce, build 02c1d87
恭喜了,docker已下载安装成功。May the docker be with you.
touch Dockerfile
# Use an official Python runtime as a parent image
FROM python:2.7-slim
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
ADD . /app
# Install any needed packages specified in requirements.txt
RUN pip install -r requirements.txt
# Make port 80 available to the world outside this container
EXPOSE 80
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["python", "app.py"]
app.py
和项目依赖requirements.txt
。requirements.txt
Flask
Redis
app.py
from flask import Flask
from redis import Redis, RedisError
import os
import socket
# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)
app = Flask(__name__)
@app.route("/")
def hello():
try:
visits = redis.incr("counter")
except RedisError:
visits = "cannot connect to Redis, counter disabled"
html = "Hello {name}!
" \
"Hostname: {hostname}
" \
"Visits: {visits}"
return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80)
pip install -r requirements.txt
安装项目依赖。friendlyhello
或者自定义名称。docker build -t friendlyhello .
也可通过命令查看docker现在所有的镜像(image)。
$ docker images
REPOSITORY TAG IMAGE ID
friendlyhello latest 326387cea398
-p
命令映射端口4000到容器开放的端口80:docker run -p 4000:80 friendlyhello
-d
,停止时使用docker stop CONTAINER_ID
,CONTAINER_ID就是app的容器id。$ docker run -d -p 4000:80 friendlyhello
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED
1fa4ab2cf395 friendlyhello "python app.py" 28 seconds ago
$ docker stop 1fa4ab2cf395
o(^▽^)o 恭喜,app已成功的在docker中运行起来。可以在浏览器中通过http://localhost:4000
访问app。或者通过curl
访问:
$ curl http://localhost:4000
<h3>Hello World!h3><b>Hostname:b> 8fc990912a14<br/><b>Visits:b> <i>cannot connect to Redis, counter disabledi>