Docker: Create an Application with Python and MongoDB

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

Docker is a software platform that allows developers to create and run applications in containers. Containers are software units that contain everything needed to run an application, including the code, libraries, and dependencies. In this tutorial, I will show you how to use Docker to create a Python application with MongoDB.

Step 1: Install Docker

To use Docker, you first need to install it on your computer. You can download Docker from the official Docker website (https://www.docker.com/get-started).

Step 2: Create a MongoDB Container

To use MongoDB in Docker, you need to create a MongoDB container. You can do this using the following command in the terminal:

docker run --name mongo-db -d mongo

This command will create a MongoDB container named “mongo-db”.

Step 3: Create a Python Application

To create a Python application that uses MongoDB in Docker, you need to create a Dockerfile. The Dockerfile defines how the application container will be built. Here is an example of a Dockerfile for a Python application with MongoDB:

FROM python:3.9

WORKDIR /app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

ENV MONGO_DB_URL mongodb://mongo-db:27017/mydatabase

CMD [ "python", "./app.py" ]

This Dockerfile uses the Python 3.9 image as the base. It copies the application files to the working directory “/app” and then installs the dependencies using the “requirements.txt” file. It then defines the environment variable “MONGO_DB_URL”, which specifies the MongoDB database URL, and finally executes the “app.py” file.

Step 4: Create the Python Application

Now that you have the Dockerfile, you can create the Python application. Here is a basic example of a Python application that uses MongoDB:

from pymongo import MongoClient

client = MongoClient("mongodb://mongo-db:27017/")
db = client["mydatabase"]

collection = db["users"]
collection.insert_one({"name": "John", "age": 25})

print("User inserted into the database.")

This code creates a connection to the MongoDB database using the URL defined in the “MONGO_DB_URL” environment variable. It then inserts a document into the “users” collection and finally prints a message to the console.

Step 5: Build and Run the Container

Now that you have the Dockerfile and the Python application, you can build the application container using the following command in the terminal:

docker build -t myapp .

This command will build the application container using the Dockerfile and assign it the name “myapp”.

Finally, you can run the container using the following command in the terminal:

docker run --name myapp --link mongo-db:mongo-db myapp

This command will run the application container and link it to the MongoDB container you created earlier. You should now see the message “User inserted into the database” in the console.

Leave a Comment