Python docker容器没有同时运行



我尝试从单个存储库启动3个docker容器。我的文件树是这样的

.
├── docker
│   ├── inf1
│   │   └── Dockerfile
│   ├── inf2
│   │   └── Dockerfile
│   └── proc1
│       └── Dockerfile
├── docker-compose.yaml
├── example
│   ├── __init__.py
│   ├── infinite_process1.py
│   ├── infinite_process2.py
│   └── stop_process.py
├── exe_inf1.py
├── exe_inf2.py
└── exe_proc.py

infinite_process1.pyinfinite_process2.py包含无限循环过程,使用while True像这样

# ./example/infinite_process1.py
# ./example/infinite_process2.py
import time

class InfiniteProcess1:  # InfiniteProcess2 respectively
def __init__(self):
pass
def infinite_loop(self):
while True:
print("InfProcess 1")
time.sleep(2)

./example/stop_process.py是这样的。它不会无限运行

# ./example/stop_process.py
class SimpleProcess:
def __init__(self, name_: str):
self.my_name = name_
def run(self):
print(f"my name is {self.my_name}")

exe_inf1.pyexe_inf2.pyexe_proc.py分别在infinite_process1.pyinfinite_process2.pystop_process.py中运行类。

例如,./docker/inf1/Dockerfile看起来像这样

FROM python:3.10.7
WORKDIR /app
COPY . .
ENTRYPOINT [ "python" ]
CMD [ "exe_inf1.py" ]

我想创建所有3个exe_*.py文件独立启动,所以,我创建了一个。yaml文件,像这样

version: '2'
services:
py1:
build:
context: .
dockerfile: ./docker/inf1/Dockerfile

py2:
build:
context: .
dockerfile: ./docker/inf2/Dockerfile
py3:
build:
context: .
dockerfile: ./docker/proc1/Dockerfile

然而,当docker容器成功构建时,docker容器似乎不能正确运行./exe_inf1.py./exe_inf2.py。它应该每2秒打印一次"InfProcess 1"

[+] Running 4/1
⠿ Network docker-python_default  Created                                                         0.0s
⠿ Container docker-python-py2-1  Created                                                         0.0s
⠿ Container docker-python-py3-1  Created                                                         0.0s
⠿ Container docker-python-py1-1  Created                                                         0.0s
Attaching to docker-python-py1-1, docker-python-py2-1, docker-python-py3-1
docker-python-py3-1  | my name is foo
docker-python-py3-1 exited with code 0

我的问题是:

我能做些什么使无限循环docker容器独立运行?还是我在这里做错了什么

完整的代码可以在这里找到:https://github.com/SKKUGoon/sof_question

这只是打印问题,就像@SebDieBln说的那样。

import time
class InfiniteProcess2:
def __init__(self):
pass
def infinite_loop(self):
while True:
print("InfProcess 2", flush=True)
time.sleep(2)

添加flush=True使一切正常。谢谢。

最新更新