使用django开发项目带celery服务的时候,需要同时启动3个服务,每次启动和停止服务,操作起来会很麻烦
但是Dockerfile 里面 CMD 命令只能启动一个服务,于是想到写一个start.sh
写一个start.sh 文件启动3个服务
python3 manage.py celery -A DjangoProjectName worker --loglevel=info >celery.out & python3 manage.py celery beat --loglevel=info > celery.out & python3 manage.py runserver 0.0.0.0:8000
注意:start.sh里面前面的命令以&结尾,表示后台服务,最后一个命令不以&结尾,表示前台服务,必须要这样,如果都是后台服务,则执行完会直接退出,如果都是前台服务,则只会执行第一条命令。
shutdown.sh 文件内容
ps -aux | grep python| awk '{print $2}' | xargs kill -9
使用ps查看python相关进程,kill 杀掉
FROM python:3.6.8 MAINTAINER yoyo <283340479@qq.com> # 替换debian镜像地址改成阿里云地址解决update更新慢的问题 RUN sed -i s@/deb.debian.org/@/mirrors.aliyun.com/@g /etc/apt/sources.list RUN apt-get update RUN apt-get -y install vim RUN apt-get -y install lrzsz RUN pip install --upgrade pip --index-url https://pypi.douban.com/simple # 创建work目录 WORKDIR /code ADD . /code # 安装依赖包 RUN pip install -r requirements.txt --index-url https://pypi.douban.com/simple # 同步数据库 RUN python manage.py makemigrations RUN python manage.py migrate # 给sh文件执行权限 RUN chmod u+x ./start.sh RUN chmod u+x ./shutdown.sh # 开放端口 EXPOSE 8000 # 执行启动服务命令 ENTRYPOINT ["sh"] CMD ["./start.sh"]
Dockerfile中ENTRYPOINT和CMD的区别,参考这篇https://www.jianshu.com/p/54cfa5721d5f
django项目根目录有了Dockefile和start.sh文件后,就可以构建本地镜像
docker build -t yoyo .
启动容器
docker run -d -p 8000:8000 --name a1 yoyo
查看容器运行日志
docker logs -f a1(容器id或name)
进入容器内部
docker exec -it a1(容器id或name) bash
查看容器内部已启动的服务ps -ef | grep python
# docker exec -it a1 bash root@4a08a0f8ac55:/code# ps -ef | grep python root 7 1 0 11:01 ? 00:00:02 python3 manage.py celery -A DjangoProjectName worker --loglevel=info root 8 1 0 11:01 ? 00:00:01 python3 manage.py celery beat --loglevel=info root 9 1 0 11:01 ? 00:00:00 python3 manage.py runserver 0.0.0.0:8000 root 19 9 1 11:01 ? 00:00:22 /usr/local/bin/python3 manage.py runserver 0.0.0.0:8000 root 26 7 0 11:01 ? 00:00:00 python3 manage.py celery -A DjangoProjectName worker --loglevel=info root 28 7 0 11:01 ? 00:00:00 python3 manage.py celery -A DjangoProjectName worker --loglevel=info root 29 7 0 11:01 ? 00:00:00 python3 manage.py celery -A DjangoProjectName worker --loglevel=info root 30 7 0 11:01 ? 00:00:00 python3 manage.py celery -A DjangoProjectName worker --loglevel=info root 31 7 0 11:01 ? 00:00:00 python3 manage.py celery -A DjangoProjectName worker --loglevel=info root 32 7 0 11:01 ? 00:00:00 python3 manage.py celery -A DjangoProjectName worker --loglevel=info root 33 7 0 11:01 ? 00:00:00 python3 manage.py celery -A DjangoProjectName worker --loglevel=info root 34 7 0 11:01 ? 00:00:00 python3 manage.py celery -A DjangoProjectName worker --loglevel=info root 35 7 0 11:01 ? 00:00:00 python3 manage.py celery -A DjangoProjectName worker --loglevel=info root 36 7 0 11:01 ? 00:00:00 python3 manage.py celery -A DjangoProjectName worker --loglevel=info root 47 39 0 11:20 pts/0 00:00:00 grep python
停掉容器服务
docker stop a1(容器id或name)
重新启动容器
docker start a1(容器id或name)
删除容器(删除容器必须先停掉容器,才能rm删除)
docker rm a1(容器id或name)