【发布时间】:2026-02-18 10:40:01
【问题描述】:
我正在尝试在 docker 中运行一个数据库,并使用它运行一个 python 脚本来存储 MQTT 消息。这给了我使用 Docker Compose 的想法,因为听起来两者都有一定的联系是合乎逻辑的。我遇到的问题是 Docker 容器确实可以运行,但它们不会在数据库中存储任何内容。
当我在本地运行我的脚本时,它确实存储了消息,所以我的预感是 Compose 文件不正确。 这是编写将消息存储在数据库和数据库本身中的python文件的正确方法(使用.js文件作为凭据)。任何反馈将不胜感激!
version: '3'
services:
storing_script:
build:
context: .
dockerfile: Dockerfile
depends_on: [mongo]
mongo:
image: mongo:latest
environment:
MONGO_INITDB_ROOT_USERNAME: xx
MONGO_INITDB_ROOT_PASSWORD: xx
MONGO_INITDB_DATABASE: motionDB
volumes:
- ${PWD}/mongo-data:/data/db
- ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
ports:
- 27018:27018
restart: unless-stopped
用于构建的 DockerFile:
# set base image (host OS)
FROM python:3.8-slim
# set the working directory in the container
WORKDIR /code
# copy the dependencies file to the working
directory
COPY requirements.txt .
# install dependencies
RUN pip install -r requirements.txt
# copy the content of the local src directory to
the working directory
COPY src/ .
# command to run on container start
CMD [ "python", "./main.py"]
【问题讨论】:
-
如果你在Windows上运行,我相信docker数据文件夹需要的权限是Windows文件系统无法满足的,所以你必须使用docker卷。不确定这是否已在您使用的任何版本中得到修复,或者是否与您的问题有关。
-
@Llama 在 linux 上运行,容器确实运行,但每当我发送 mqtt 消息时,我都没有得到响应。我到处都有打印语句,但感觉好像我的 python 文件和数据库没有链接或连接
标签: mongodb docker docker-compose dockerfile