install Python in Alpine Linux with docker support

In this tutorial, we’ll walk through the process of creating a Docker image for a Python application using Alpine Linux. Alpine Linux is a lightweight distribution, making it a popular choice for Docker images due to its reduced size. Below are given the steps to achieve this task.

Step 1: Create a Dockerfile

At the very beginning, let’s create a file named Dockerfile in your project directory with the following content:

# Use the official Alpine Linux image with Python 3.9
FROM python:3.9-alpine

# Set the working directory
WORKDIR /app

# Copy source code
COPY . .

# Install dependencies
RUN apk add --no-cache build-base libffi-dev openssl-dev \
    && pip install --upgrade pip \
    && pip install -r requirements.txt

# Expose port and set environment variable
EXPOSE 80
ENV NAME World

# Run the application
CMD ["python", "app.py"]

In our Dockerfile we created above:

  • We use the official Python 3.9 Alpine image as the base.
  • Set the working directory to /app.
  • Copy the local source code into the container.
  • Install necessary dependencies using apk and Python packages using pip.
  • Expose port 80 and set an environment variable.
  • After that, specify the command to run when the container starts.

Step 2: Prepare the Application

Make sure that our Python application code is in the same directory as the Dockerfile. If you have dependencies, create a requirements.txt file with them.

Step 3: Build the Docker Image

Open a terminal and navigate to the project directory. Next, run the following command to build our Docker image:

docker build -t your-image-name .

Replace your-image-name with the name for your Docker image.

Step 4: Run the Docker Container

Once the image has been built, we can run a container based on it. Use the following command for this:

docker run -p 4000:80 your-image-name

Replace 4000 with the desired host port you want.

Visit http://localhost:4000 in your browser to see your Python application running inside a Docker container! If everything is right, then it should work.

Feel free to customize the Dockerfile based on your project’s specific requirements. Dockerizing your Python application allows for easier deployment and distribution across different environments.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top