Python Probe with Docker Python

Enabling the Python Probe

Before being able to profile, you need to add the Probe to your Docker Python image. Here is an example of a Dockerfile based on the official Docker Python image:

Caution

Please note that Blackfire Probe for Python does not support Alpine at the moment.

1
2
3
FROM python:3.7-buster

RUN pip install --upgrade pip blackfire

Note

Base image

This example targets official Python Docker images. If you are using a custom image, you will probably want to adapt it.

Build your container as usual:

1
docker build -t python-blackfire .

Note

Upgrading

To upgrade the Probe, rebuild your Python container and relaunch it (you might need to use the --no-cache option to force the download of the latest Probe version).

Docker Compose

Within a docker-compose context, you may take inspiration from the following snippet to connect your Python container and the agent:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
version: '3'
services:
  app:
    build: .
    ports:
      - "8080:80"

  blackfire:
    image: blackfire/blackfire:2
    environment:
        # Exposes BLACKFIRE_SERVER_* environment variables from the host
        BLACKFIRE_SERVER_ID: ~
        BLACKFIRE_SERVER_TOKEN: ~
        # You can also use global environment credentials
        # BLACKFIRE_SERVER_ID: SERVER-ID
        # BLACKFIRE_SERVER_TOKEN: SERVER-TOKEN

Using the Client for CLI Profiling

When profiling command line scripts, the process is slightly different than for HTTP requests. You execute blackfire run which in the end runs an embedded agent and wraps your Python script with the required environment variables. Therefore, in this configuration you do not need to (and cannot) use the blackfire/blackfire image. Instead, you need to fetch and use the blackfire client binary inside your Python container.

Installing Blackfire Client

Here is an example of a Dockerfile based on the official Docker Python image that retrieves the client at build time:

1
2
3
4
5
6
7
8
FROM python:3.7-buster

RUN pip install --upgrade pip blackfire
RUN mkdir -p /tmp/blackfire \
    && architecture=$(case $(uname -m) in i386 | i686 | x86) echo "i386" ;; x86_64 | amd64) echo "amd64" ;; aarch64 | arm64 | armv8) echo "arm64" ;; *) echo "amd64" ;; esac)
    && curl -A "Docker" -L https://blackfire.io/api/v1/releases/cli/linux/$architecture | tar zxp -C /tmp/blackfire \
    && mv /tmp/blackfire/blackfire /usr/bin/blackfire \
    && rm -Rf /tmp/blackfire

Build your container as usual:

1
docker build -t python-blackfire .

Debugging the Python Probe

By default, the Probe is quiet and does not produce logs. To debug issues, pass -e BLACKFIRE_LOG_LEVEL=4 to the docker run command, and tail the logs via Docker:

1
docker logs -f PYTHON_CONTAINER_ID

Installing the Agent

To install the Blackfire Agent using Docker, please refer to the dedicated documentation page.