build docker image in python

To build a Docker image in Python, you need to create a Dockerfile in your project directory with the instructions for building the image. Here's an example Dockerfile.

main.py
# Use an official Python runtime as a parent image
FROM python:3.6-slim-stretch

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]
521 chars
21 lines

Here's what each instruction does:

  • FROM specifies the base image for the Docker image. In this case, we are using the official Python 3.6 slim-stretch image.
  • WORKDIR sets the working directory to /app in the container.
  • COPY copies the contents of the current directory (our Python code) into the /app directory in the container.
  • RUN runs the specified command (pip install ...) in the container.
  • EXPOSE specifies that port 80 in the container should be exposed.
  • ENV sets the environment variable NAME to World.
  • CMD specifies the command to run when the container is launched.

To build the Docker image, navigate to your project directory in the terminal and run the following command:

docker build -t myimage .
26 chars
2 lines

This will build the Docker image using the Dockerfile in the current directory and tag it as myimage.

gistlibby LogSnag