Docker image linux python

Build your Python image

Estimated reading time: 13 minutes

Prerequisites

Work through the orientation and setup in Get started Part 1 to understand Docker concepts.

Enable BuildKit

Before we start building images, ensure you have enabled BuildKit on your machine. BuildKit allows you to build Docker images efficiently. For more information, see Building images with BuildKit.

BuildKit is enabled by default for all users on Docker Desktop. If you have installed Docker Desktop, you don’t have to manually enable BuildKit. If you are running Docker on Linux, you can enable BuildKit either by using an environment variable or by making BuildKit the default setting.

To set the BuildKit environment variable when running the docker build command, run:

To enable docker BuildKit by default, set daemon configuration in /etc/docker/daemon.json feature to true and restart the daemon. If the daemon.json file doesn’t exist, create new file called daemon.json and then add the following to the file.

Restart the Docker daemon.

Overview

Now that we have a good overview of containers and the Docker platform, let’s take a look at building our first image. An image includes everything needed to run an application — the code or binary, runtime, dependencies, and any other file system objects required.

To complete this tutorial, you need the following:

  • Python version 3.8 or later. Download Python
  • Docker running locally. Follow the instructions to download and install Docker
  • An IDE or a text editor to edit files. We recommend using Visual Studio Code.

Sample application

Let’s create a simple Python application using the Flask framework that we’ll use as our example. Create a directory in your local machine named python-docker and follow the steps below to create a simple web server.

Now, let’s add some code to handle simple web requests. Open this working directory in your favorite IDE and enter the following code into the app.py file.

Test the application

Let’s start our application and make sure it’s running properly. Open your terminal and navigate to the working directory you created.

To test that the application is working properly, open a new browser and navigate to http://localhost:5000 .

Switch back to the terminal where our server is running and you should see the following requests in the server logs. The data and timestamp will be different on your machine.

Create a Dockerfile for Python

Now that our application is running properly, let’s take a look at creating a Dockerfile.

A Dockerfile is a text document that contains the instructions to assemble a Docker image. When we tell Docker to build our image by executing the docker build command, Docker reads these instructions, executes them, and creates a Docker image as a result.

Let’s walk through the process of creating a Dockerfile for our application. In the root of your project, create a file named Dockerfile and open this file in your text editor.

What to name your Dockerfile?

The default filename to use for a Dockerfile is Dockerfile (without a file- extension). Using the default name allows you to run the docker build command without having to specify additional command flags.

Some projects may need distinct Dockerfiles for specific purposes. A common convention is to name these Dockerfile. or .Dockerfile . Such Dockerfiles can then be used through the —file (or -f shorthand) option on the docker build command. Refer to the “Specify a Dockerfile” section in the docker build reference to learn about the —file option.

We recommend using the default ( Dockerfile ) for your project’s primary Dockerfile, which is what we’ll use for most examples in this guide.

The first line to add to a Dockerfile is a # syntax parser directive. While optional, this directive instructs the Docker builder what syntax to use when parsing the Dockerfile, and allows older Docker versions with BuildKit enabled to upgrade the parser before starting the build. Parser directives must appear before any other comment, whitespace, or Dockerfile instruction in your Dockerfile, and should be the first line in Dockerfiles.

Читайте также:  Как быстро переименовать файл windows

We recommend using docker/dockerfile:1 , which always points to the latest release of the version 1 syntax. BuildKit automatically checks for updates of the syntax before building, making sure you are using the most current version.

Next, we need to add a line in our Dockerfile that tells Docker what base image we would like to use for our application.

Docker images can be inherited from other images. Therefore, instead of creating our own base image, we’ll use the official Python image that already has all the tools and packages that we need to run a Python application.

To learn more about creating your own base images, see Creating base images.

To make things easier when running the rest of our commands, let’s create a working directory. This instructs Docker to use this path as the default location for all subsequent commands. By doing this, we do not have to type out full file paths but can use relative paths based on the working directory.

Usually, the very first thing you do once you’ve downloaded a project written in Python is to install pip packages. This ensures that your application has all its dependencies installed.

Before we can run pip3 install , we need to get our requirements.txt file into our image. We’ll use the COPY command to do this. The COPY command takes two parameters. The first parameter tells Docker what file(s) you would like to copy into the image. The second parameter tells Docker where you want that file(s) to be copied to. We’ll copy the requirements.txt file into our working directory /app .

Once we have our requirements.txt file inside the image, we can use the RUN command to execute the command pip3 install . This works exactly the same as if we were running pip3 install locally on our machine, but this time the modules are installed into the image.

At this point, we have an image that is based on Python version 3.8 and we have installed our dependencies. The next step is to add our source code into the image. We’ll use the COPY command just like we did with our requirements.txt file above.

This COPY command takes all the files located in the current directory and copies them into the image. Now, all we have to do is to tell Docker what command we want to run when our image is executed inside a container. We do this using the CMD command. Note that we need to make the application externally visible (i.e. from outside the container) by specifying —host=0.0.0.0 .

Here’s the complete Dockerfile.

Directory structure

Just to recap, we created a directory in our local machine called python-docker and created a simple Python application using the Flask framework. We also used the requirements.txt file to gather our requirements, and created a Dockerfile containing the commands to build an image. The Python application directory structure would now look like:

Build an image

Now that we’ve created our Dockerfile, let’s build our image. To do this, we use the docker build command. The docker build command builds Docker images from a Dockerfile and a “context”. A build’s context is the set of files located in the specified PATH or URL. The Docker build process can access any of the files located in this context.

The build command optionally takes a —tag flag. The tag is used to set the name of the image and an optional tag in the format name:tag . We’ll leave off the optional tag for now to help simplify things. If you do not pass a tag, Docker uses “latest” as its default tag.

Let’s build our first Docker image.

View local images

To see a list of images we have on our local machine, we have two options. One is to use the CLI and the other is to use Docker Desktop. As we are currently working in the terminal let’s take a look at listing images using the CLI.

Читайте также:  Отличие обычного windows от серверного

To list images, simply run the docker images command.

You should see at least two images listed. One for the base image 3.8-slim-buster and the other for the image we just built python-docker:latest .

Tag images

As mentioned earlier, an image name is made up of slash-separated name components. Name components may contain lowercase letters, digits and separators. A separator is defined as a period, one or two underscores, or one or more dashes. A name component may not start or end with a separator.

An image is made up of a manifest and a list of layers. Do not worry too much about manifests and layers at this point other than a “tag” points to a combination of these artifacts. You can have multiple tags for an image. Let’s create a second tag for the image we built and take a look at its layers.

To create a new tag for the image we’ve built above, run the following command.

The docker tag command creates a new tag for an image. It does not create a new image. The tag points to the same image and is just another way to reference the image.

Now, run the docker images command to see a list of our local images.

You can see that we have two images that start with python-docker . We know they are the same image because if you take a look at the IMAGE ID column, you can see that the values are the same for the two images.

Let’s remove the tag that we just created. To do this, we’ll use the rmi command. The rmi command stands for remove image.

Note that the response from Docker tells us that the image has not been removed but only “untagged”. You can check this by running the docker images command.

Our image that was tagged with :v1.0.0 has been removed, but we still have the python-docker:latest tag available on our machine.

Next steps

In this module, we took a look at setting up our example Python application that we will use for the rest of the tutorial. We also created a Dockerfile that we used to build our Docker image. Then, we took a look at tagging our images and removing images. In the next module we’ll take a look at how to:

Feedback

Help us improve this topic by providing your feedback. Let us know what you think by creating an issue in the Docker Docs GitHub repository. Alternatively, create a PR to suggest updates.

Источник

Dockerize your Python Application

Dockerfiles enable you to create your own images. A Dockerfile describes the software that makes up an image. Dockerfiles contain a set of instructions that specify what environment to use and which commands to run.

Creating a Dockerfile

First, start with a fresh empty directory. In our example, we call this my_new_docker_build – but feel free to use whatever name you like. This directory defines the context of your build, meaning it contains all of the things you need to build your image.

Create a new text file in my_new_docker_build called Dockerfile (note no extension; on Windows, you may need to save the file as “All types” and put the filename in quotes to avoid automatically appending an extension); use whatever text file editor you already know (you might use Sublime, Notepad++, emacs, nano, or even vi). In our example, we use the basic Python 3 image as our launching point. Add the following line to your Dockerfile:

We want to run a basic Python script which we’ll call my_script.py . First, we need to add the script to the Dockerfile:

Our script depends on the Python pyStrich library (pyStrich generates 1D and 2D barcodes), so we need to make sure we install that before we run my_script.py ! Add this line to your Dockerfile to install random:

Add this line to your Dockerfile to execute the script:

Читайте также:  Файл подкачки astra linux

Your Dockerfile should look like this:

  • FROM tells Docker which image you base your image on (in the example, Python 3).
  • RUN tells Docker which additional commands to execute.
  • CMD tells Docker to execute the command when the image loads.

The Python script my_script.py looks like the following:

Now you are ready to build an image from this Dockerfile. Run:

Run Your Image

After your image has been built successfully, you can run it as a container. In your terminal, run the command docker images to view your images. You should see an entry for “python-barcode”. Run the new image by entering:

You should see what looks like a large ASCII QR code.

Alternatives

If you only need to run a simple script (with a single file), you can avoid writing a complete Dockerfile. In the examples below, assume you store my_script.py in /usr/src/widget_app/ , and you want to name the container my-first-python-script :

Python 3:

Python 2:

Further information

Creating a Dockerfile

Make sure you do not append an extension to the Dockerfile (i.e., Docker does not recognize Dockerfile.txt ).

You do not have to read the contents of every Dockerfile you base yours on, but make sure to at least familiarize yourself with them; you can avoid trying to install redundant software (e.g., installing pip when the Python image already loads it), and you can make sure you write your RUN commands appropriately. Docker Hub does not enforce basing all images off only one distribution of Linux; if you use a Debian-based distribution (Debian, Ubuntu, Mint, etc.) you need to call apt-get to install software, and if you use a Red Hat-based distribution (Red Hat Enterprise Linux/RHEL, CentOS) you need to use yum . Gaining familiarity early prevents redoing your work and saves time.

You might end up starting with an unfamiliar base image (i.e., if you primarily use CentOS and want to run a Python installation, the Python image extends Debian Jessie, so you need to use caution in how you write your RUN directives). If you maintain familiarity with Ubuntu, using Debian does not offer too many challenges (Ubuntu came from an offshoot of Debian Linux).

Avoid putting any unused files in your build directory. Docker makes tarballs of everything in the current directory and sends that to the Docker daemon, so if you have unnecessary files, those are included.

Alternatives

Do not attempt to run a script requiring dependencies using the Alternative method, unless those dependencies come with the bare Python installation.

Deleting Docker Containers

Run the following command from your docker console to see a list of your containers:

Note: Removing a Container is FINAL.

Delete a Single Container

  1. Run docker ps -a and retrieve the container ID (an alphanumeric string, something like a39c259df462 ).
  2. Run docker rm a39c259df462 to remove just that container.

Delete All Your Containers

To delete all your containers, run:

  • -q prints only the container ID’s
  • -a prints all containers
  • passing all container IDs to xargs, docker rm deletes all containers

Deleting Docker Images

Delete a Single Image

  1. Retrieve the Image ID using docker images (The Image IDs should be in the third column.)
  2. Run docker rmi

Delete All Untagged Images

This requires a little bit of Linux magic (like deleting all containers above). Docker marks images without tags with » » so we need to process only those images. Run the following command from your terminal (the awk programming language gives you text manipulation tools):

Delete All Images

To delete all of your images, you can simplify the command above:

Delete Docker Containers

Usage:

Command Deletes
all All containers
$ The container corresponding to the container ID you pass

Delete Docker Images

Usage:

Command Deletes
all All images
untagged Images tagged with “ » (untagged images)
$ The image corresponding to the Image ID you pass

Next: Dockerize your Django Application
Get started with dockerizing your Django application.

By Runnable: The service that speeds up development by providing full-stack environments for every code branch.

Источник

Оцените статью