Skip to content

Instantly share code, notes, and snippets.

@revenkroz
Last active March 28, 2024 14:50
Show Gist options
  • Save revenkroz/931d868748232efd884be3a6c278144a to your computer and use it in GitHub Desktop.
Save revenkroz/931d868748232efd884be3a6c278144a to your computer and use it in GitHub Desktop.

How to install and use PHP XHProf in Docker

1. Add Dockerfile with XHProf module and GUI

FROM php:8.1-fpm-alpine AS xhprof

WORKDIR /app

# graphviz and ttf-freefont are required to vizualize functions calls
RUN apk update && apk add git autoconf make g++ graphviz ttf-freefont
RUN git clone https://github.com/longxinH/xhprof.git ./xhprof && \
    cd xhprof/extension/ && \
    phpize && \
    ./configure && \
    make && \
    make install
RUN apk del git autoconf make g++

RUN echo $'extension = xhprof.so \n\
    xhprof.output_dir = /app/var/xhprof' > /usr/local/etc/php/conf.d/xhprof.ini

WORKDIR /app/xhprof/xhprof_html

CMD ["/usr/local/bin/php", "-S", "0.0.0.0:8090"]

EXPOSE 8090

Or without alpine:

FROM php:8.1-fpm AS xhprof

WORKDIR /www

# graphviz and ttf-freefont are required to vizualize functions calls
RUN apt update && apt install -y git autoconf make g++ graphviz fonts-freefont-ttf
RUN git clone https://github.com/longxinH/xhprof.git ./xhprof && \
    cd xhprof/extension/ && \
    phpize && \
    ./configure && \
    make && \
    make install

RUN echo 'extension = xhprof.so \n\
    xhprof.output_dir = /www/xhprof/xhprof_runs' > /usr/local/etc/php/conf.d/xhprof.ini

WORKDIR /www/xhprof/xhprof_html

CMD ["/usr/local/bin/php", "-S", "0.0.0.0:8090"]

EXPOSE 8090

If you use docker compose don't forget to add configuration:

services:
    xhprof:
        restart: unless-stopped
        build:
            context: ./
            dockerfile: .docker/php/Dockerfile # path to your XHProf Dockerfile
            target: xhprof
        ports:
            - "8090:8090"
        volumes:
            - .:/app

2. Add to your app's Dockerfile

# ...

# Install XHProf extension
COPY --from=xhprof /app/xhprof/extension/modules/xhprof.so /tmp/xhprof.so
RUN mv /tmp/xhprof.so $(php-config --extension-dir)/xhprof.so
COPY --from=xhprof /usr/local/etc/php/conf.d/xhprof.ini /usr/local/etc/php/conf.d/xhprof.ini

# ...

3. Wrap you code

xhprof_enable();

// app code
// ...
// end app code

$xhprofData = xhprof_disable();

$XHPROF_ROOT = '/app/xhprof'; // or any other path to php lib
include_once $XHPROF_ROOT . '/xhprof_lib/utils/xhprof_lib.php';
include_once $XHPROF_ROOT . '/xhprof_lib/utils/xhprof_runs.php';

$xhprofRuns = new \XHProfRuns_Default();
$runId = $xhprofRuns->save_run($xhprofData, 'my_app');

4. Visit GUI

http://localhost:8090

5. Analyze!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment