Dockerizing a Python App

Dockerizing a Python App

·

2 min read

In this tutorial, we'll guide you through the process of Dockerizing a Python application and deploying it on App Server. The task involves creating a Dockerfile, building a Docker image, and running a container with specific configurations.

Prerequisites:

  • Access to App Server.

  • Basic knowledge of Docker and Python.

Task Overview:

The task requires Dockerizing a Python application located under the /python_app/src directory on App Server. The Dockerfile must install dependencies from the requirements.txt file and run the server.py script as the entry point. Additionally, the container should expose port 8085 and map it to port 8092 on the host.

1. SSH into the Host Server:

First, establish an SSH connection to App Server where the Python application is located.

ssh user@app_server3_ip

Replace user with your username and app_server3_ip with the IP address of App Server.

2. Create the Dockerfile:

Navigate to the /python_app directory and create a Dockerfile with the following content:

FROM python:3

WORKDIR /usr/src/app

COPY requirements.txt ./

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

COPY . .

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

EXPOSE 8085

This Dockerfile specifies to use the official Python 3 image as the base, sets the working directory, copies the requirements.txt file, installs dependencies, copies the application files, sets the command to run the server.py script, and exposes port 8085.

3. Build the Docker Image:

Execute the following command to build the Docker image named nautilus/python-app:

docker build -t nautilus/python-app .

This command builds the Docker image based on the Dockerfile in the current directory (.) and tags it as nautilus/python-app.

4. Run the Docker Container:

Next, run a container named pythonapp_nautilus using the built image and map port 8085 on the container to port 8092 on the host:

docker container run -d --name pythonapp_nautilus -p 8092:8085 nautilus/python-app

This command starts a Docker container in detached mode (-d), names it pythonapp_nautilus, and maps port 8085 in the container to port 8092 on the host.

5. Verify the Deployment:

To verify that the Python application is running successfully, use curl to send a request to the application endpoint:

curl http://localhost:8092

This command should return the response from the Python application, indicating that it is up and running.

Conclusion:

In this tutorial, you learned how to Dockerize a Python application and deploy it on App Server using Docker containers. By following the provided steps, you can efficiently package and deploy Python applications in Dockerized environments, facilitating easier management and scalability of your applications.