第5次系统综合实践作业

一、自定义python镜像

pull python镜像

sudo docker pull python

编写相关文件

  • Dockerfile文件:
FROM python
MAINTAINER zlrong
WORKDIR /app
COPY ./requirements.txt /requirements.txt
RUN pip install -r /requirements.txt -i https://pypi.douban.com/simple  #修改源并安装依赖
ENTRYPOINT ["python"]
CMD ["hello.py"] #默认打开文件
  • requirements.txt文件:
PyMySQL
opencv-python

build python镜像

sudo docker build -t mypython .

二、Hello World

hello.py

print('hello world!')

运行容器

sudo docker run -it --rm -v /home/zlr/mypython/app:/app mypython hello.py

三、日历输出

date.py

import calendar
 
# 输入指定年月
yy = int(input("输入年份: "))
mm = int(input("输入月份: "))
 
# 显示日历
print(calendar.month(yy,mm))

运行容器

sudo docker run -it --rm -v /home/zlr/mypython/app:/app mypython date.py

四、mysql数据库操作

启动mysql容器

sudo docker run --name lrmysql -d lrmysql

db.py

import pymysql

# 连接数据库
db = pymysql.connect("lrmysql", "lrong", "666", "docker_mysql")


cursor = db.cursor()
#查询user
sql = """select * FROM user"""
cursor.execute(sql)
results = cursor.fetchall()
print(results)

#insert
sql="""insert user(id,name,email,age)
	values(1,'gln','[email protected]',21)"""
cursor.execute(sql)
db.commit()
print("insert succeed!")

#select again
sql = """select * FROM user"""
cursor.execute(sql)
results = cursor.fetchall()
print(results)

#close connection
db.close()

运行容器

sudo docker run -it --rm -v /home/zlr/mypython/app:/app mypython db.py

在mysql容器中验证结果

五、opencv.py

opencv.py

import cv2
img=cv2.imread('Snoopy.jpg',flags=1)
rows,cols=img.shape[:2]
M=cv2.getRotationMatrix2D((cols/2,rows/2),270,1)
dst=cv2.warpAffine(img,M,(cols,rows))
cv2.imwrite("Snoopy-rotated.jpg", dst, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
print('rotated and saved.')

运行容器

sudo docker run -it --rm -v /home/zlr/mypython/app:/app mypython opencv.py


六、遇到的问题及解决方法

问题1在mypython构建成功后运行容器时出现了如下问题:

解决方案:通过查错,发现是mypython镜像构建有问题,所以删了构建过的镜像,重新构建。
问题2在用python连接数据库时,出现错误“docker:Error response from daemon:Cannot link to a non running container:/lrmysql AS /vigilant_dewdney/lrmysql”,但是已经运行了lrmysql容器
解决方案:重新构建lrmysql镜像并运行容器。

七、实验心得

本次实验比较容易,花费的时间大概4个小时左右。可能就是在连接数据库的时候用的时间比较久一点,还是得耐心一点。这次实践作业也体会到了docker的快速便捷的优点,也更加熟悉了之前的实验操作。

猜你喜欢

转载自www.cnblogs.com/lrongblog/p/12933852.html