我有一个具有下一个结构的 python 应用程序:
./DB
./lib
./docker-compose.yml
./Dockerfile
./module1.py
./module2.py
./module3.py
./app_run.sh
./requirements.txt
我想得到什么
我的应用程序镜像大约为 1.5G,所以我想要实现的是拥有一个应用程序镜像,能够使用唯一的某个模块运行多个容器。这样我就可以使用 module1.py 脚本(或任何其他脚本)或许多此类脚本来运行容器。
通过这种方式,我希望加快这个过程,因为不需要每次都构建应用程序镜像,只需连接到它。
为什么我需要从 app shell 脚本运行这样的容器。
shell 脚本从外部源获取所需的参数,如 URL 和 token ,然后在模块中使用。
shell 脚本的结构如下:
#!/bin/sh
ip=$1
url=$2
token=$3
folder="./temp/"
folder_oss='./temp/DB/TEST/'
db_folder="./temp/DB"
app="./"
name=$(date '+%Y%m%d%H%M%S')
cd $folder && mkdir -p "$folder$name"
folder="$folder$name"
cd $app
if [ $ip = 1 ]; then
python3.6 ./module1.py -u $url -t $token -f $folder -d $db_folder
status=${PIPESTATUS};
elif [ $ip = 3 ]; then
python3.6 ./module2.py -u $url -t $token -f $folder |& tee "$folder/logtemp.txt"
status=${PIPESTATUS};
elif [ $ip = 7 ]; then
python3.6 ./module.py -u $url -t $token -f $folder -d $db_folder |& tee "$folder/load_logtemp.txt"
status=${PIPESTATUS};
else
echo "Error while predicting"
status=1;
fi
我想我应该写一些类似 docker container run 的东西,而不是 python3.6 ./module1.py。但是我应该如何将这些模块指定为单独的容器?
目前,我的 Dockerfile 看起来像这样:
FROM python:3.6
COPY . /app
WORKDIR /app
RUN pip freeze > requirements.txt
EXPOSE 7524
CMD ["./app_run.sh", "1","link/to/settings.json, "token"]
还有 docker_compose.yml:
version: "2"
services:
app:
build: .
environment:
- DB_HOST=mysql
- DB_PORT=7524
ports:
- 8080:8080
depends_on:
- mysql
mysql:
image: mysql:latest
restart: always
environment:
- MYSQL_USER=user
- MYSQL_ROOT_PASSWORD=54321
ports:
- 7524:3303
volumes:
- my-db:/var/lib/mysql
volumes:
my-db:
最佳答案
移动app_run.sh
到入口点并将模块名称和 IP、 token 等传递给 CMD
.你的 Dockerfile 看起来像
FROM python:3.6
COPY . /app
WORKDIR /app
EXPOSE 7524
RUN chmod +x app_run.sh
ENTRYPOINT ["./app_run.sh"]
CMD ["1","link/to/settings.json","token"]
然后在
entrypoint
中处理这些参数在你的情况下,它是 app_run.sh`#!/bin/sh
ip=$1
url=$2
token=$3
echo "IP is $ip , URL is $url , token is $token"
mkdir temp
folder="./temp/"
folder_oss='./temp/DB/TEST/'
db_folder="./temp/DB"
app="./"
name=$(date '+%Y%m%d%H%M%S')
cd $folder
mkdir -p "$folder$name"
folder="$folder$name"
cd $app
if [ $ip = 1 ]; then
python3.6 ./module1.py -u $url -t $token -f $folder -d $db_folder
status=${PIPESTATUS};
elif [ $ip = 3 ]; then
python3.6 ./module2.py -u $url -t $token -f $folder
status=${PIPESTATUS};
elif [ $ip = 7 ]; then
python3.6 ./module.py -u $url -t $token -f $folder -d $db_folder
status=${PIPESTATUS};
else
echo "Error while predicting"
status=1;
fi
记住一件事,如果 python 在前台运行并且它的长时间运行的进程那么它的状态将无法到达
status=${PIPESTATUS};
所以如果你想使用 运行容器IP 3 , 一切你需要的
docker run -it --rm my_image "3" "link/to/settings.json" "token
默认情况下,它将使用 IP 1 运行。
关于docker - 如何根据参数从 shell 脚本启动 Docker 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58753752/