Docker Container exits

Hello Guys,

I wrote a Dockerfile which takes the mongo image as a base image and copys 2 scripts. When I run them seperately everything works fine, but it doesn’t with the dockerfile.


FROM mongo

# Install Python 3, Pip, Pandas, and PyMongo

RUN apt-get update && apt-get install -y python3 python3-pip \

&& python3 -m pip install --no-cache-dir pandas pymongo

# Kopieren Sie das Init-Script, das Python-Skript und das CSV-Datei in den Container

COPY /docker-entrypoint-initdb.d/


COPY iot_telemetry_data.csv /

# Definieren Sie die Standard-Command für den Container

CMD ["bash", "-c", "mongod --fork --logpath /var/log/mongodb.log && python3"]

bash script:


# Führen Sie die Initialisierungsaufgaben aus, z. B. das Erstellen der Datenbank und Sammlung
mongo portfolio_database --eval 'db.createCollection("co2_data")'

python script :

# importing the needed libraries
import pandas as pd
from pymongo import MongoClient

# Connecting to the MongoDB Database
client = MongoClient("localhost", 27017)
db = client["portfolio_database"]
collection = db["co2_data"]

#Reading CSV File and storing it to the collection 
chunk_size = 500
for chunk in pd.read_csv("iot_telemetry_data.csv", chunksize=chunk_size):
    # Daten in MongoDB einfügen
    records = chunk.to_dict(orient="records")

print("Import completed.")

Everything is saved in the same directory. I tried to force the container to keep running, but when I do that connecting to the database is not possible… Even tried to debug with the help of ChatGPT, but it can’t find a solution… will run in the entrypoint but how would run when you first run the mongo daemon so nothing after that can run? would run only after the daemon stopped. I would not change the CMD at all.

Initializing a fresh instance

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongosh (mongo on versions below 6) using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

so if you can use any mongo command when the daemon is still not running or a js file that will be run by mongosh, you can add more init script to the entrypoint. Otherwise all you can do is use docker exec or docker compose exec after the mongo daemon started and connect to it from a separate container.