目录
本文环境:
CentOS Stream 8
Docker 20.10.13
本文创建一个用python连接redis数据,输出到网页功能的镜像。
1.创建文件夹/mydocker以及如下文件
2.编辑Dockerfile
FROM python:2.7-slim
WORKDIR /app
ADD . /app
VOLUME ["/data_flask"]
#安装requirements.txt库制作镜像时运行
RUN pip install --trusted-host pypi.python.org -r requirements.txt
EXPOSE 80
ENV NAME World
ENV AUTHOR Seesunman
#容器启动时运行
CMD ["python","app.py"]
3.编辑requirements.txt文件
Flask
Redis
4.编辑app.py文件
from flask import Flask
from redis import Redis, RedisError
import os
import socket
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 = "<i>cannot connect to Redis, Counter disabled</i>"
html = "<h3>Hello {name}!</h3>" \
"<b>Hostname:</b> {hostname}<br/>" \
"<b>Vistor:</b> {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)
5.生成镜像文件
docker build -t sc_friend .
Sending build context to Docker daemon 4.608kB
Step 1/9 : FROM python:2.7-slim
---> eeb27ee6b893
Step 2/9 : WORKDIR /app
---> Using cache
---> 783796e25280
Step 3/9 : ADD . /app
---> Using cache
---> ad51881385b8
Step 4/9 : VOLUME ["/data_flask"]
---> Using cache
---> 6ff70abee09d
Step 5/9 : RUN pip install --trusted-host pypi.python.org -r requirements.txt
---> Using cache
---> 047a6b325e6b
Step 6/9 : EXPOSE 80
---> Using cache
---> 99eac2430436
Step 7/9 : ENV NAME World
---> Using cache
---> 1718fa0344ea
Step 8/9 : ENV AUTHOR Seesunman
---> Using cache
---> 7a4d5d5259ba
Step 9/9 : CMD ["python","app.py"]
---> Using cache
---> e1821c89e957
Successfully built e1821c89e957
Successfully tagged sc_friend:latest
6.查看镜像
[root@Seesunman mydocker]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
sc_friend latest e1821c89e957 15 minutes ago 159MB
7.启动容器
docker run -d -p 6379:6379 --name sc-redis-1 redis
docker run -d -p 8081:80 --link sc-redis-1:redis --name sc-hello-2 sc_friend
#需要启动一个redis容器,和我们制作镜像的容器
8.访问网站
如果没启动redis容器,访问不了数据库会显示如下