背景介绍:
本项目使用Springboot编写服务端口,python实现爬虫任务,bash脚本完成任务调度。出于环境搭建过于繁琐的考虑,本项目希望采用容器化技术完成一键部署,简化操作流程。
主要内容:
本文主要介绍如何使用Docker进行环境的搭建和部署。
运行环境:
腾讯云轻量应用服务器 Ubuntu20.04
阿里云数据库mysql
- 安装Docker
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
⚠️ **注意2375端口!**建议关闭Docker的远程操作api端口,以免服务器遭到劫持。
- 寻找合适的基础镜像
由于本项目需要python
和java
的双重环境,所以我们在Dockerhub上寻找合适的镜像源。
这个库可以满足需求。
- 设置Dockerfile
# 获得一个base镜像 里面包含java和python3环境
FROM blindspotsolutions/jdk-python:v0.0.1-openjdk8u242-python3.7-slim-buster
# https://hub.docker.com/r/blindspotsolutions/jdk-python/tags
# FROM jdk-python
# FROM python:3.6.9
MAINTAINER chenE2000 # 作者
WORKDIR /app # 进入工作文件夹
COPY requirements.txt .
# 安装python依赖,加载镜像源加速
RUN pip install -r requirements.txt -i https://pypi.doubanio.com/simple --trusted-host pypi.doubanio.com
COPY . .
EXPOSE 8888 # 暴露8888端口
CMD ./start-all.sh # 启动脚本
- 设置启动脚本
由于我们的项目启动需要Springboot作为后台,python实现爬虫,所以需要两行命令,但是查看官方文档:
It’s ok to have multiple processes, but to get the most benefit out of Docker, avoid one container being responsible for multiple aspects of your overall application. You can connect multiple containers using user-defined networks and shared volumes.
官方不提倡一个容器负责多个任务,但也存在解决方案(原文)
我们构建如下的启动脚本,并在Dockerfile
的最后一行运行。
# start-all.sh 总任务脚本,开启多个任务
time=`date +%Y-%m-%d`
# 开启爬虫定时任务
echo "0 3 * * * root /app/start-clawler.sh" >> /etc/crontab
# 开启java后台服务
java -jar ./RemindsMeOfElectricity.jar &
# Wait for any process to exit
wait $!
# Exit with status of process that exited first
exit $?
其中爬虫开启如下,将日志保存在容器中:
time=`date +%Y-%m-%d`
# 注意路径,和Dockerfile中的WORKDIR有关系
python /app/main.py > /app/logs/$time.log 2>&1 &
- 构建镜像
$ docker build -t reminds_me_of_electricity .
- 启动服务
$ docker run -d -p 8888:8888 reminds_me_of_electricity
相关命令:
进入正在运行的容器
$ sudo docker ps
$ sudo docker exec -it 775c7c9ee1e1 /bin/bash
删除过多的images
$ docker system prune -a
$ echo "* * * * * root hostname >> /tmp/tmp.txt" >> /etc/crontab
参考博客
https://docs.docker.com/engine/security/protect-access/#related-information
https://www.runoob.com/docker/docker-dockerfile.html
https://blog.csdn.net/weixin_42054155/article/details/90815393
https://cloud.tencent.com/developer/article/1334959
https://blog.csdn.net/qq_20042935/article/details/105043400
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/120017214
https://blog.csdn.net/mzc11/article/details/81842534
https://blog.csdn.net/weixin_36088159/article/details/113053044
https://docs.docker.com/config/containers/multi-service_container/