Меню

Вывод ошибок php docker

How can I access the php error logs for my container?

For some reason I’m really struggling to find out how to do this after a long time of searching various articles.

I’m using a simple php7 apache container which looks like:
FROM php:7-apache

RUN apt-get update -y && apt-get install -y 
        libpng12-dev 
        libfreetype6-dev 
        libjpeg62-turbo-dev 
        curl 
        libcurl4-openssl-dev 
        libxpm-dev 
        libvpx-dev 
    && docker-php-ext-configure gd 
    --with-freetype-dir=/usr/lib/x86_64-linux-gnu/ 
    --with-jpeg-dir=/usr/lib/x86_64-linux-gnu/ 
    --with-xpm-dir=/usr/lib/x86_64-linux-gnu/ 
    --with-vpx-dir=/usr/lib/x86_64-linux-gnu/ 
    && docker-php-ext-install 
        pdo 
        pdo_mysql 
        gd 
        curl 
    && a2enmod rewrite 
    && service apache2 restart

Ideally I just need to view the contents of the error log or get a new custom log set locally on my machine so I easily see potential issues with my site build.

Any pointers appreciated. I found the docker documentation very confusing on the topic of logs…

asked Aug 23, 2017 at 12:09

Gerico's user avatar

It exists the following docker command:

docker logs -f --details containerName

that will show you the mysql and php errors log files

for more check the documentation: docker logs

answered Aug 23, 2017 at 12:11

Edwin's user avatar

EdwinEdwin

2,07620 silver badges26 bronze badges

5

By default the container doesn’t seem to log PHP errors to STDOUT or STDERR. I found that when using the php.ini-development config file (see ‘Configuration’ in this article) it logs a lot more useful information.

To view the logs for a container, the most basic way is to do docker ps, find the container hash, and then do docker logs container_hash.

answered Jul 12, 2020 at 11:17

Jimbali's user avatar

JimbaliJimbali

1,8271 gold badge17 silver badges22 bronze badges

1

All PHP output will be in the container, so you can use all the docker goodies to access the logs…

My favorite is attach as it allows you to follow the logs in real time. ( docker attach containerName )

There’s also logs to see the past logs. docker logs containerName will print out all the output from the container. You might prefer adding the --tail=N flag where N is the number of lines to get.

answered Aug 23, 2017 at 12:16

Salketer's user avatar

SalketerSalketer

13.7k2 gold badges29 silver badges57 bronze badges

Mateusz Cholewka

If you are using docker and cloud services to run your application live, you should manage your logs.

The most common method to store them is to put them in the text file. It’s the default configuration for most backend frameworks. This option is ok if you run your application locally or on the VPS server for test.

When you run your application in a production environment, you should choose a better option to manage your logs. Almost every cloud has a tool for rotating logs or if not, you can use for example Grafana Loki or ELK stack. Those solutions are better because give you interfaces to rotate and search your logs. Also, you have easy access to them, you no need to connect to your server to review them.

If you are using Docker containers, and you running your application in cloud services, often they will be automatically writing the logs of your containers to tools like AWS CloudWatch or GCloud Stackdriver.

But first, you need to redirect your log streams to the output of the Docker container to be able to use them.

Linux streams

Docker containers are running the Linux processes. In linux every running process has 3 streams, STDIN, STDOUT, STDERR. STDIN it’s command input stream, that you can provide for ex. by your keyboard. STDOUT is the stream where the running command may print the output. STDERR is the standard error stream, but the name I think is a bit confusing, because it is basically intended for diagnostic output.

When you run the docker logs [container] command in your terminal, you will see the output of STDOUT and STDERR streams. So our goal is to redirect our logs to one of those streams.

Official docker documentation page

PHP-FPM

In PHP we are often running our application using the PHP-FPM (Process Manager). If you run your docker with FPM inside a docker container, and you run the docker logs command, you should see the output with processed requests, or errors.

So the PHP-FPM is already writing its output to STDOUT.

The PHP-FPM allow us to catch workers output and forward them to the STDOUT. To do that we need to make sure that the FPM is configured properly. You can create new config file, and push it for example to the /usr/local/etc/php-fpm.d/logging.conf file:

[global]
error_log = /proc/self/fd/2

[www]
access.log = /proc/self/fd/2

catch_workers_output = yes
decorate_workers_output = no

Enter fullscreen mode

Exit fullscreen mode

The error_log and access.log parameters are configuration of streams of logs output.

The catch_workers_output option is turning on the worker’s output caching. The decorate_workers_output is the option that turns off the output decoration. If you leave this option turned on, FPM will decorate your application output like this:

[21-Mar-2016 14:10:02] WARNING: [pool www] child 12 said into stdout: "[your log line]"

Enter fullscreen mode

Exit fullscreen mode

Remember that decorate_workers_output option is available only for PHP 7.3.0 and higher.

If you are using official docker php-fpm image, this configuration is already set in the /usr/local/etc/php-fpm.d/docker.conf file, so you no need to do anything more 😎

PHP application configuration

Right now everything that will be put to the stdout from PHP workers will be shown in our docker logs. But when logs are forwarded to that stream in PHP?

To write something to STDIN on PHP level, we need to just write to the php://stdout stream.

In the simplest way you can do this like that:

<?php

file_put_contents('php://stdout', 'Hello world');

Enter fullscreen mode

Exit fullscreen mode

When you execute this code in php cli, you will get the Hello world text on the output.

But it’s not the optimal way to push your logs to the STDOUT. Every modern framework should have a PSR-3 Logger. I think that the most popular now is the monolog, so I will show you how to configure it in Symfony, Laravel, and in pure usage.

Monolog

Monolog is great library to handle logs in your application. It’s easy and elastic in configuration.

Basic monolog configuration

If you are using monolog in your project with manual configuration, you need to configure handler in this way:

(Modified documentation example)

<?php

use MonologLogger;
use MonologHandlerStreamHandler;

$log = new Logger('stdout');
$log->pushHandler(new StreamHandler('php://stdout', Logger::DEBUG));

$log->debug('Foo');

Enter fullscreen mode

Exit fullscreen mode

You just need to configure StreamHandler, to write to the php://stdout file.

Symfony

Symfony Kernel since the Flex was provided, is using minimalist PSR-3 logger, that logs everything to php://stderr by default.

In Symfony, monolog as other components is configured in YAML files. So the same configuration will look like this:

# config/packages/monolog.yaml
monolog:
    handlers:
        stdout:
            type: stream
            path: "php://stdout"
            level: debug

Enter fullscreen mode

Exit fullscreen mode

Laravel

Laravel use the arrays for configuration so the same thing will look like this:

# config/logging.php
<?php

use MonologHandlerStreamHandler;

return [
    'channels' =>
        'stdout' => [
            'driver' => 'monolog',
            'handler' => StreamHandler::class,
            'level' => env('LOG_LEVEL', 'debug'),
            'with' => [
                'stream' => 'php://stdout',
            ],
        ],
];

Enter fullscreen mode

Exit fullscreen mode

STDERR or STDOUT

In some articles on the internet, you can read that someone uses stderr, and someone uses stdout streams to write logs there. Right now I cannot fin any reasons to choose one of them which is better.

The only information that I found on this topic is that post.

I think that stderr is more popular in some examples, also Fabien Potencier set it as default in his minimalistic logger, so I think we can assume that this one is better.

Personally, I always used the stdout, so that’s the reason why I use it in this post’s examples. If I will find a great reason for using one of them over another I will update this post.

Originally posted on https://mateuszcholewka.com

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

keltik85 opened this issue

Apr 1, 2016

· 10 comments


Closed

Where is the error.log?

#212

keltik85 opened this issue

Apr 1, 2016

· 10 comments

Comments

@keltik85

Hi,

I need some advice from more seasoned docker users.

I am extending the official php-image in my Dockerfile like this:

 FROM php:5.6-apache
        MAINTAINER "John Doe <Johndoe@dough.com>"
        COPY ./templates/apache2files/piwik /var/www/html/
        COPY ./templates/php.ini /usr/local/etc/php/
        RUN chmod 777 -R /var/www/html/
        RUN docker-php-ext-install mysqli
        RUN docker-php-ext-install mbstring

I build the dockerfile with this:

I run the container like this:

docker run -d --name mypiwikcontainer -p "8888:80" mypiwik:latest

I can see the access.log using this:

docker logs mypiwikcontainer

How can I see the error.log?????

DMW007, supersv, gabrielef, jszoja, CrlsMrls, strarsis, sushrest, Amunak, 0redd, QuinnBast, and 3 more reacted with thumbs up emoji

@tdutrion

Hi,

What have you got in your logs? (docker logs mypiwikcontainer)

Currently I have the following (version 7.0-apache):

[core:warn] [pid 1] AH00111: Config variable ${APACHE_RUN_DIR} is not defined

Therefore, there might be no file, unless I actually set this variable (currently investigation).

Also, you do not need to access the file. You can probably read it by connecting with ssh (docker exec -it mypiwikcontainer /bin/bash), and then access the right directory and use less or whatever is installed. I would personally use docker logs and am trying to get into the log drivers to centralise logs to a central graylog instance.

@blueimp

@keltik85
I had the same issue and solved it the following way:

In your php.ini, add the following lines:

log_errors = On
error_log = /dev/stderr

Now you’ll be able to see any PHP error logs as part of the docker container log stream:

docker logs -f your_php_apache_container

To display only errors and hide the access log, you can pipe stdout to /dev/null:

docker logs -f your_php_apache_container >/dev/null

To follow only the access log, you can pipe stderr to /dev/null:

docker logs -f your_php_apache_container 2>/dev/null
keltik85, Denys-Bushulyak, DonovanChan, jmcvetta, traneHead, max3-05, droath, hypnoboutique, shamil8124, Skysplit, and 131 more reacted with thumbs up emoji
afonsocarlos, rubik, HadesArchitect, and oliverll1 reacted with hooray emoji
nathanmartins, dambrogia, sklochko-id, ksm2, ChristophWurst, fezfez, Mykola-Veryha, mohsentm, rivetmichael, QuentinouLeTwist, and 21 more reacted with heart emoji

@povils

It’s cool, but how to get actual log files?

@Raaghu

check that 000-default site is enabled for your apache,
in my case /etc/apache2/sites-enabled/ does not contained softlink to 000-default.conf

so I ran

a2ensite 000-default
apache2ctl restart

then i started seeing logs in access.log and error.log

@mikesparr

@povils Container apps shouldn’t write log files in the container, as its lifecycle is meant to be «disposable», unless you mount a volume and want them on your file system. This is a core tenet of the 12-factor-app methodology.

  • see: https://12factor.net/logs

If you docker exec -it app-name ls -alh /var/log/apache2/ you will see the log files are symlinked to /dev/stderr and /dev/stdout as they should. This allows the container engine to expose logs via the docker logs -f app-name command or an orchestrator like Swarm or Kubernetes to expose them to centralized logging like ELK stack or Stackdriver.

vadimslu, vphantom, fredericomartini, redhat-raptor, alwinmarkcf, oradwell, craigiswayne, raknjak, abdulladev1995, derekrprice, and 4 more reacted with thumbs up emoji

@povils

@mikesparr Thanks for the answer. I needed log files because I am using Elastic Filebeat which harvests log files and streams that to our ELK

@mikesparr

I believe you enable fluentd and configure logging output. The ephemeral nature of containers is meant to stream logs not write them so you need to capture the stream one layer up, then ship em.

Sent from my iPhone

On Oct 20, 2017, at 2:51 AM, Povilas Susinskas ***@***.***> wrote:

@mikesparr Thanks for the answer. I needed log files because I am using Elastic Filebeat which harvests log files and streams that to our ELK


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub, or mute the thread.

@okainov

@blueimp thanks, works perfectly! I wonder, why isn’t it included into default PHP Docker image….

@buster95

I solved this problem adding next command in dockerfile

RUN cp $PHP_INI_DIR/php.ini-development $PHP_INI_DIR/php.ini

@Videles

@keltik85 I had the same issue and solved it the following way:

In your php.ini, add the following lines:

log_errors = On
error_log = /dev/stderr

Now you’ll be able to see any PHP error logs as part of the docker container log stream:

docker logs -f your_php_apache_container

To display only errors and hide the access log, you can pipe stdout to /dev/null:

docker logs -f your_php_apache_container >/dev/null

To follow only the access log, you can pipe stderr to /dev/null:

docker logs -f your_php_apache_container 2>/dev/null

This works like a charms, thanks a lot!

Before we start…

The previous post about dockerising a PHP application (which you should read if you haven’t) got a lot more attention than I ever imagined, which is AWESOME. However, while introducing some of  the suggested improvements a number discrepencies between the contents of the blog post and the GitHub repository emerged. Buuut…

The death of php-docker.local

The initial setup included a step that required you to update your hosts file and add an entry for php-docker.local. I received feedback from several people that this step is not completely clear and they ended up skipping it. It turns out this step can be removed easily, so why don’t we just go ahead and do it 🙂

Two things are needed to achieve this. First, we have to update the site.conf in order to handle the connections to localhost. Second, the default configuration in the Nginx image should be replaced with our new config.
For the first part we have to replace the server_name setting with:

    server_name localhost;

and add the following setting:

    listen 80;

Now our site.conf will look like this:

server {
    listen 80;
    index index.php index.html;
    server_name localhost;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /code;

    location ~ .php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

In order to replace the default Nginx config we have to mount our site.conf in its place. To achieve that we have to tweak our docker-compose.yml a bit. The end result will look like this:

web:
    image: nginx:latest
    ports:
        - "8080:80"
    volumes:
        - ./code:/code
        - ./site.conf:/etc/nginx/conf.d/default.conf
    links:
        - php
php:
    image: php:7-fpm
    volumes:
        - ./code:/code

For those who missed it, we changed one of the volumes for the web container with the following:

        - ./site.conf:/etc/nginx/conf.d/default.conf

Now your PHP application will be accessible on any domain pointing to your Docker host.

Docker-compose v2

For a while now docker-compose supports version 2 for the docker-compose files, which adds some improvements to the setup. Let’s see how the docker-compose.yml will look like using the new format:

version: 2

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - ./code:/code
            - ./site.conf:/etc/nginx/conf.d/site.conf
    php:
        image: php:7-fpm
        volumes:
            - ./code:/code

This doesn’t look much different, except that we don’t have to specify the links between the containers. Docker-compose adds all the containers to the same network and they are “linked” by default. This is especially useful when you add more containers to the setup (e.g. database, cache, queue, etc.) since you don’t have to worry about specifing the links between containers.

Another thing the we can do using version 2 of the docker-compose files is to specify networks for the containers. For example:

version: 2

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - ./code:/code
            - ./site.conf:/etc/nginx/conf.d/default.conf
        networks:
            - code-network
    php:
        image: php:fpm
        volumes:
            - ./code:/code
        networks:
            - code-network

networks:
    code-network:
        driver: bridge

This option allows grouping different containers in different networks based on the services they need to connect to. In our setup this is not needed, but I believe it’s an important feature to be aware of, especially when expanding the setup with more services.

Special thanks to cipriantepes, who contributed to the repository with this improvement.

PHP logging to stdout

This is something trivial but I never really thought it’s needed until I got several requests and even a PR for it. The issue is that the default php-fpm Docker image is not configured to log the errors. The fix is to enable logging.

First, let’s add a log.conf file with the following content:

php_admin_flag[log_errors] = on
php_flag[display_errors] = off

Next, add this to the configuration of the PHP container:

 version: '2'

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - ./code:/code
            - ./site.conf:/etc/nginx/conf.d/default.conf
        networks:
            - code-network
    php:
        image: php:fpm
        volumes:
            - ./code:/code
            - ./log.conf:/usr/local/etc/php-fpm.d/zz-log.conf
        networks:
            - code-network

networks:
    code-network:
        driver: bridge

So… what happened? Well, we mounted our new log file in the PHP container, but we added a zz- prefix to it. Why? Because we want to have this configuration loaded last, so that it’s not overriden by the rest of the configs.
Here’s the line for the curious:

            - ./log.conf:/usr/local/etc/php-fpm.d/zz-log.conf

Since this wasn’t part of the initial blog post, it resides in a separate branch – feature/log-to-stdout.

Final summation

I guess no matter how good you make something, there’s always room for improvement. In that sense, any remarks and PRs are more than welcome 🙂

You can find the updated code here – https://github.com/mikechernev/dockerised-php

this is my docker-compose.yml:

services:
 nginx:
 image: nginx:stable-alpine
 container_name: nginx
 ports:
            - "8088:8088"
            - "80:80" 
 volumes:            
            - ./php-fpm:/var/www/html 
            - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
php:        
 build:
 context: ./php-fpm
 dockerfile: Dockerfile
 container_name: php
 user: "1000:1000"
 volumes:
            - ./php-fpm:/var/www/html
 ports:
            - "9000:9000""

This is my nginx default.conf:

server {
    listen 8088;
    index index.php index.html;    
    error_log /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/html/public;
    
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    location ~ .php$ {        
        try_files $uri = 404;
        fastcgi_split_path_info ^(.+.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
    
}

}

Can’t find the error log inside the containers…

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Вывод ошибок mysql php
  • Вывод ошибки mysql query