Docker服务之间共享的Python模块

kknvjkwl  于 2023-03-29  发布在  Docker
关注(0)|答案(1)|浏览(121)

我有一个这样的项目结构:

stack-example/service1
├── Dockerfile
└── main.py
stack-example/service2
├── Dockerfile
└── main.py
stack-example/shared_module
├── __init__.py
└── utils.py
stack-example/docker-compose.yml
  • service 1 * 和 * service 2 * 都使用 shared_module
#service1/main.py == service2/main.py
from shared_module import print_hello

def main():
    print_hello()

if __name__ == "__main__":
    main()

所以我有两个Dockerfile

#service1/Dockerfile (service2 has the same idea)
FROM python:3.11-slim

WORKDIR /service1

USER 1002

COPY . .

docker-compose.yml

version: '3.3'

services:
  service1:
    build: service1/.
    command: python3 main.py
    ports:
      - 8012:8012

  service2:
    build: service2/.
    command: python3 main.py
    ports:
      - 8013:8013

当然,如果我尝试运行它,我会得到Python import error,因为他显然看不到 shared_module
我应该在我的源文件和docker文件中添加什么来实现所需的行为?

qybjjes1

qybjjes11#

在@ViaTech评论的帮助下,我找到了一个解决方案:

  • Dockerfile* 应该是这样的:
FROM python:3.11-slim

WORKDIR /service1

USER 1002

COPY ./service1 /service1
COPY ./shared_module /service1/shared_module

docker-compose.yml应该看起来像这样:

version: '3.3'

services:
  service1:
    build:
      context: ./
      dockerfile: ./service1/Dockerfile
    command: python3 main.py

  service2:
    build:
      context: ./
      dockerfile: ./service2/Dockerfile
    command: python3 main.py

相关问题