How To Create Minimal Docker Photographs for Python Purposes

How To Create Minimal Docker Photographs for Python Purposes
Picture by Editor | Midjourney & Canva

 

Creating minimal Docker photographs for Python apps enhances safety by decreasing the assault floor, facilitates sooner picture builds, and improves total utility maintainability. Let’s discover ways to create minimal Docker photographs for Python purposes.

 

Conditions

 

Earlier than you get began:

  • It is best to have Docker put in. Get Docker on your working system should you haven’t already.
  • A pattern Python utility that you must construct the minimal picture for. You can too observe together with the instance app we create.

Create a Pattern Python Software

 

Let’s create a easy Flask utility for stock administration. This utility will let you add, view, replace, and delete stock objects. We’ll then dockerize the appliance utilizing the usual Python 3.11 picture.

In your undertaking listing, it’s best to have app.py, necessities.txt, and Dockerfile:

inventory_app/
├── app.py
├── Dockerfile
├── necessities.txt

 

Right here’s the code for the Flask app for stock administration:

# app.py
from flask import Flask, request, jsonify

app = Flask(__name__)

# In-memory database for simplicity
stock = {}

@app.route('/stock', strategies=['POST'])
def add_item():
    merchandise = request.get_json()
    item_id = merchandise.get('id')
    if not item_id:
        return jsonify({"error": "Merchandise ID is required"}), 400
    if item_id in stock:
    	return jsonify({"error": "Merchandise already exists"}), 400
    stock[item_id] = merchandise
    return jsonify(merchandise), 201

@app.route('/stock/', strategies=['GET'])
def get_item(item_id):
    merchandise = stock.get(item_id)
    if not merchandise:
        return jsonify({"error": "Merchandise not discovered"}), 404
    return jsonify(merchandise)

@app.route('/stock/', strategies=['PUT'])
def update_item(item_id):
    if item_id not in stock:
        return jsonify({"error": "Merchandise not discovered"}), 404
    updated_item = request.get_json()
    stock[item_id] = updated_item
    return jsonify(updated_item)

@app.route('/stock/', strategies=['DELETE'])
def delete_item(item_id):
    if item_id not in stock:
        return jsonify({"error": "Merchandise not discovered"}), 404
    del stock[item_id]
    return '', 204

if __name__ == '__main__':
	app.run(host="0.0.0.0", port=5000)

 

This can be a minimal Flask utility that implements fundamental CRUD (Create, Learn, Replace, Delete) operations for an in-memory stock database. It makes use of Flask to create an internet server that listens for HTTP requests on port 5000. When a request is obtained:

  • For a POST request to /stock, it provides a brand new merchandise to the stock.
  • For a GET request to /stock/<item_id>, it retrieves the merchandise with the desired ID from the stock.
  • For a PUT request to /stock/<item_id>, it updates the merchandise with the desired ID within the stock.
  • For a DELETE request to /stock/<item_id>, it deletes the merchandise with the desired ID from the stock.

Now create the necessities.txt file:

 

Subsequent create the Dockerfile:

# Use the official Python 3.11 picture
FROM python:3.11

# Set the working listing
WORKDIR /app

# Set up dependencies
COPY necessities.txt necessities.txt
RUN pip set up --no-cache-dir -r necessities.txt

# Copy the present listing contents into the container at /app
COPY . .

# Expose the port the app runs on
EXPOSE 5000

# Run the appliance
CMD ["python3", "app.py"]

 

Lastly construct the picture (we use the tag full to determine that this makes use of the default Python picture):

$ docker construct -t inventory-app:full .

 

As soon as the construct is full you possibly can run the docker photographs command:

$ docker photographs
REPOSITORY      TAG                 IMAGE ID       CREATED             SIZE
inventory-app   full                4e623743f556   2 hours in the past         1.02GB

 

You’ll see that this tremendous easy app is about 1.02 GB in measurement. Properly, it is because the bottom picture we used the default Python 3.11 picture has numerous Debian packages and is about 1.01 GB in measurement. So we have to discover a smaller base picture.

Properly, listed below are the choices:

  • python:version-alpine photographs are primarily based on Alpine Linux and will provide you with the smallest ultimate picture. However you want to have the ability to set up packages as properly, sure? However that’s a problem with alpine photographs.
  • python:version-slim comes with the minimal variety of Debian packages wanted to run Python. And also you’ll (virtually all the time) have the ability to set up most required Python packages with pip.

So your base picture ought to be small. However not too small that you simply face compatibility points and wrap your head round putting in dependencies (fairly frequent for Python purposes). That’s why we’ll use the python:3.11-slim base picture within the subsequent step and construct our picture.

 

base-imagebase-image
Selecting the Optimum Base Picture | Picture by Writer

 

 

Use the Slim Python Base Picture

 

Now rewrite the Dockerfile to make use of the python:3.11-slim base picture like so:

# Use the official light-weight Python 3.11-slim picture
FROM python:3.11-slim

# Set the working listing
WORKDIR /app

# Set up dependencies
COPY necessities.txt necessities.txt
RUN pip set up --no-cache-dir -r necessities.txt

# Copy the present listing contents into the container at /app
COPY . .

# Expose the port the app runs on
EXPOSE 5000

# Run the appliance
CMD ["python3", "app.py"]

 

Let’s construct the picture (tagged slim):

$ docker construct -t inventory-app:slim .

 

The python:3.11-slim base picture is of measurement 131 MB. And the inventory-app:slim picture is round 146 MB which is far smaller than the 1.02GB picture we had earlier:

$ docker photographs
REPOSITORY      TAG                 IMAGE ID       CREATED             SIZE
inventory-app   slim                32784c60a992   About an hour in the past   146MB
inventory-app   full                4e623743f556   2 hours in the past         1.02GB

 

You can too use multi-stage builds to make the ultimate picture smaller. However that is for an additional tutorial!

Extra Assets

 

Listed here are a number of helpful sources:

 

 

Bala Priya C is a developer and technical author from India. She likes working on the intersection of math, programming, information science, and content material creation. Her areas of curiosity and experience embody DevOps, information science, and pure language processing. She enjoys studying, writing, coding, and occasional! Presently, she’s engaged on studying and sharing her information with the developer neighborhood by authoring tutorials, how-to guides, opinion items, and extra. Bala additionally creates participating useful resource overviews and coding tutorials.


Leave a Reply