Python Probe with Docker

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

Build your container as usual:

1
docker build -t python-blackfire .

Docker Compose

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

 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
    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
FROM python:3.7-buster

RUN pip install --upgrade pip blackfire
RUN mkdir -p /tmp/blackfire \
    && curl -A "Docker" -L https://blackfire.io/api/v1/releases/client/linux_static/amd64 | 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 .

Installing the Site-Specific Configuration Hook

In order to profile with blackfire run without any code modification in your application, you need to install the blackfire_bootstrap.pth file as a site-specific configuration hook.

In order to do so, run the following command within your Python container:

1
python -m blackfire install-bootstrap

When running the Python container, you need to expose a BLACKFIRE_CLIENT_ID and a BLACKFIRE_CLIENT_TOKEN environment variables to allow the client to communicate with Blackfire’s API.

You can now directly execute blackfire run python my_script.py within your Python container.

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