Wow, wow, wow! Something interesting was found here!
First of all, I’m sorry for providing «buggy» PoC, which lead to wrong conclusions. Actually there is no sense of opcache
ext there. But the issue I’ve pointed to still remains.
Having Dockerfile
like:
FROM php:alpine RUN docker-php-ext-install gd
We have next successful result of docker build
(you may just check it):
$ docker build --no-cache -t test .
......................
configure: error: png.h not found.
WARNING: Ignoring APKINDEX.167438ca.tar.gz: No such file or directory
WARNING: Ignoring APKINDEX.a2e6dac0.tar.gz: No such file or directory
(1/24) Purging .phpize-deps (0)
......................
(24/24) Purging libgomp (5.3.0-r0)
Executing busybox-1.24.2-r11.trigger
OK: 16 MiB in 25 packages
---> 598ce831f3b8
Removing intermediate container c8afb81a0fca
Successfully built 598ce831f3b8
While if we are using sed
to remove subshell:
FROM php:alpine RUN sed -i -r 's/^t+($//g' /usr/local/bin/docker-php-ext-install && sed -i -r 's/^t+)$//g' /usr/local/bin/docker-php-ext-install RUN docker-php-ext-install gd
Build fails as expected at configure
step:
$ docker build --no-cache -t test .
......................
configure: error: png.h not found.
The command '/bin/sh -c docker-php-ext-install gd' returned a non-zero code: 1
And now is interesting…
I didn’t know about -e
inheritance. And reproduced your example in my macOS terminal:
$ sh -c 'set -e; echo "1"; (echo "2"; false; echo "3"); echo "4"'
1
2
It really works. But why those Dockerfile
s behave so?
That’s why:
$ docker run --rm -it alpine sh
/ # sh -c 'set -e; echo "1"; (echo "2"; false; echo "3"); echo "4"'
1
2
4
Я новичок в Docker, но мне нужно поддерживать существующую систему. Dockerfile, который я использую, как показано ниже:
FROM php:5.6-apache
RUN docker-php-ext-install mysql mysqli
RUN apt-get update -y && apt-get install -y sendmail
RUN apt-get update &&
apt-get install -y
zlib1g-dev
RUN docker-php-ext-install mbstring
RUN docker-php-ext-install zip
RUN docker-php-ext-install gd
Когда я запускаю ‘docker build [sitename]’, все выглядит нормально, пока я не получу ошибку:
configure: error: png.h not found.
The command '/bin/sh -c docker-php-ext-install gd' returned a non-zero code: 1
В чем причина этой ошибки?
22
Решение
Вы должны добавить libpng-dev
пакет к вашему Dockerfile
:
FROM php:5.6-apache
RUN docker-php-ext-install mysql mysqli
RUN apt-get update -y && apt-get install -y sendmail libpng-dev
RUN apt-get update &&
apt-get install -y
zlib1g-dev
RUN docker-php-ext-install mbstring
RUN docker-php-ext-install zip
RUN docker-php-ext-install gd
Затем перейдите в каталог с Dockerfile
и запустить:
docker build -t sitename .
Это сработало в моем случае:
Removing intermediate container f03522715567
Successfully built 9d69212196a2
Дайте мне знать, если вы получите какие-либо ошибки.
РЕДАКТИРОВАТЬ:
Вы должны увидеть что-то вроде этого:
REPOSITORY TAG IMAGE ID CREATED SIZE
sitename latest 9d69212196a2 19 minutes ago 414 MB
<none> <none> b6c69576a359 25 minutes ago 412.3 MB
EDIT2:
Просто перепроверить все:
Пожалуйста, запустите docker build
команда таким образом:
docker build -t sitename:1.0 .
(добавление :1.0
ничего не должно меняться, я добавил это только для того, чтобы иметь дополнительную строку в docker images
выход)
Затем запустите контейнер:
docker run --name sitename_test -p 80:80 sitename:1.0
Это должно работать просто отлично.
Я предположил, что Apache использует стандартный порт (80) — возможно, вам нужно настроить это. Если у вас есть другие сервисы / контейнеры, прослушивающие порт 80, вы можете сделать так, чтобы ваш контейнер прослушивал другой порт:
docker run --name sitename_test -p 8080:80 sitename:1.0
Это перенаправит трафик с порта 8080 на порт 80 «внутри» контейнера.
Обычно вы запускаете контейнер в фоновом режиме. Для этого добавьте -d
вариант к docker run
команда (но для целей тестирования вы можете опустить -d
чтобы увидеть вывод в консоли).
Если вы решили запустить контейнер в фоновом режиме, вы можете проверить журналы, используя docker logs sitename_test
, Чтобы следить за журналами (и видеть обновления в журналах) используйте -f
опция:
docker logs -f sitename_test
Надеюсь, это поможет.
52
Другие решения
Других решений пока нет …
Docker also provides a new command exec after version 1.3.X to enter the container. This method is relatively simpler. Let’s take a look at the use of this command:
1. Configure nginx
FindDocker HubNginx mirror on
[email protected]:~/nginx$ docker search nginx
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
nginx Official build of Nginx. 3260 [OK]
jwilder/nginx-proxy Automated Nginx reverse proxy for docker c... 674 [OK]
richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable ... 207 [OK]
million12/nginx-php Nginx + PHP-FPM 5.5, 5.6, 7.0 (NG), CentOS... 67 [OK]
maxexcloo/nginx-php Docker framework container with Nginx and ... 57 [OK]
webdevops/php-nginx Nginx with PHP-FPM 39 [OK]
h3nrik/nginx-ldap NGINX web server with LDAP/AD, SSL and pro... 27 [OK]
bitnami/nginx Bitnami nginx Docker Image 19 [OK]
maxexcloo/nginx Docker framework container with Nginx inst... 7 [OK]
...
Here we pull the official mirror
[email protected]:~/nginx$ docker pull nginx
After the download is complete, we can find the REPOSITORY as a mirror of nginx in the local mirror list.
[email protected]:~/nginx$ docker images nginx REPOSITORY TAG IMAGE ID CREATED SIZE nginx latest 555bbd91e13c 3 days ago 182.8 MBCreate and run the container:
docker run --name mynginx -p 80:80 -v /var/www:/var/www -v /usr/local/nginx/conf/conf.d:/etc/nginx/conf.d -d nginx
note:
-v Add file mapping relationship, so that files changed on the host can be directly mapped to the container. The directories here are mapped according to their actual situation.
After the container is created and run, nginx in the docker starts successfully, there is no need to enter the docker to start nginx again, otherwise it will prompt that ports such as 80 are occupied because nginx has been started.
At this time, you can access the domain name verification configured by nginx.
The conf.d I mapped here mainly contains the configuration file of nginx, and the configuration information of php is:
# php server { charset utf-8; client_max_body_size 128M; listen 80; ## listen for ipv4 #listen [::]:80 default_server ipv6only=on; ## listen for ipv6 server_name www.baidu.com; root /var/www; index index.php; location / { #-e means that as long as the filename exists, it is true if (!-e $request_filename){ rewrite ^(.*)$ /index.php?s=$1 last; break; } # Redirect everything that isn't a real file to index.php try_files $uri $uri/ /index.php$is_args$args; } # uncomment to avoid processing of calls to non-existing static files by Yii #location ~ .(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ { # try_files $uri =404; #} #error_page 404 /404.html; # deny accessing php files for the /assets directory location ~ ^/assets/.*.php$ { deny all; } location ~ .php$ { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass 172.17.0.3:9000; #fastcgi_pass unix:/var/run/php5-fpm.sock; try_files $uri =404; } location ~* /. { deny all; } }
Pay attention to the ip address of fastcgi_pass at the end, which is described in detail in the php configuration common problems.
2. php configuration
Find the php mirror on Docker Hub
[email protected]:~/php-fpm$ docker search php
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
php While designed for web development, the PH... 1232 [OK]
richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable ... 207 [OK]
phpmyadmin/phpmyadmin A web interface for MySQL and MariaDB. 123 [OK]
eboraas/apache-php PHP5 on Apache (with SSL support), built o... 69 [OK]
php-zendserver Zend Server - the integrated PHP applicati... 69 [OK]
million12/nginx-php Nginx + PHP-FPM 5.5, 5.6, 7.0 (NG), CentOS... 67 [OK]
webdevops/php-nginx Nginx with PHP-FPM 39 [OK]
webdevops/php-apache Apache with PHP-FPM (based on webdevops/php) 14 [OK]
phpunit/phpunit PHPUnit is a programmer-oriented testing f... 14 [OK]
tetraweb/php PHP 5.3, 5.4, 5.5, 5.6, 7.0 for CI and run... 12 [OK]
webdevops/php PHP (FPM and CLI) service container 10 [OK]
...
Here we pull the official image, the label is 5.6-fpm
[email protected]:~/php-fpm$ docker pull php:5.6-fpm
After the download is complete, we can find the mirror whose REPOSITORY is php and the label is 5.6-fpm in the local mirror list.
[email protected]:~/php-fpm$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
php 5.6-fpm 025041cd3aa5 6 days ago 456.3 MB
Create and run the php container:
docker run -p 9000:9000 --name phpfpm -v /var/www:/var/www -d php:5.6-fpm
Note that a file mapping must be created here, or there is a corresponding php code in the php container. The file mapping of nginx in the previous step is not found here. So if there is no file mapping, 127.0.0.1:9000 cannot find the file in this container.
common problem:
After starting the php container, if you access nginx: 502 Bad Gateway
Try the following:
View the ip address of the php mirror
docker inspect --format='{{.NetworkSettings.IPAddress}}' phpfpm
Such as: 192.168.4.202
Then modify the nginx conf configuration file to make the value of fastcgi_pass 192.168.4.202:9000
vim /docker/nginx/conf.d/default.conf
fastcgi_pass 192.168.4.202:9000;
After restarting the nginx container, you can access it normally.
Three. mysql configuration
Find the mysql image on Docker Hub
[email protected]:/mysql$ docker search mysql
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relati... 2529 [OK]
mysql/mysql-server Optimized MySQL Server Docker images. Crea... 161 [OK]
centurylink/mysql Image containing mysql. Optimized to be li... 45 [OK]
sameersbn/mysql 36 [OK]
google/mysql MySQL server for Google Compute Engine 16 [OK]
appcontainers/mysql Centos/Debian Based Customizable MySQL Con... 8 [OK]
marvambass/mysql MySQL Server based on Ubuntu 14.04 6 [OK]
drupaldocker/mysql MySQL for Drupal 2 [OK]
azukiapp/mysql Docker image to run MySQL by Azuki - http:... 2 [OK]
...
Here we pull the official image, the label is 5.6
[email protected]:~/mysql$ docker pull mysql:5.6
After the download is complete, we can find the mirror with REPOSITORY as mysql and label as 5.6 in the local mirror list.
[email protected]:~/mysql$ docker images |grep mysql
mysql 5.6 2c0964ec182a 3 weeks ago 329 MB
Create and run the MySQL container:
docker run -p 3306:3306 --name mysql -v /usr/local/mysql:/etc/mysql/sqlinit -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.6
The main purpose of the file mapping here is to map the sql database data file of the host machine to the docker mysql container for easy import. Note that the directory of the mysql container here cannot be an existing directory, otherwise it will be overwritten.
note:
It is easy to create here. My.cnf already exists, so you don’t need to add it yourself.
Expand
Use the external tool Navicat to connect to mysql in docker
The host of mysql fills in the IP in docker, and the method of obtaining is:
1 docker inspect --format='{{.NetworkSettings.IPAddress}}' mysql
Fill in the ssh connection information:
Then the connection is successful!
note:
The docker container startup sequence problem will cause the container’s IP address to be inconsistent. If the container’s IP is used when connecting to the database and fastcgi, pay attention to the container’s startup sequence.
Restart the container: docker restart container name/container ID
Close the container: docker stop xxx
Start the container: docker start xxx
View the running container: docker ps
View all containers (including containers that are not running): docker ps -a
Create and run the container: docker run
—————————————
Common errors:
1. thinkphp reports an error Undefined class constant’MYSQL_ATTR_INIT_COMMAND’
Lack of pdo_mysql extension, failed to link to the database
Find php.ini, copy a copy of php.ini in /usr/local/etc/php in docker and addextension=pdo_mysql.so Restart phpfpm.
If it still doesn’t work, visit the phpinfo page to see if there is pdo_mysql
If not, say that the name extension does not exist and needs to be compiled.
The compilation method is as follows:
Can be achieved in two ways
Method one (not verified):
pecl pdo_msql
Method two (verified and feasible):
Go to the docker php container, under the php folder:
docker-php-ext-install pdo pdo_mysql
If it reports /usr/local/bin/docker-php-ext-enable: cannot create /usr/local/etc/php/conf.d/docker-php-ext-pdo_mysql.ini: Directory nonexistent
solution:
Create a new conf.d directory and the corresponding docker-php-ext-pdo_msql.ini file directly under the /usr/local/etc/php directory
The content of docker-php-ext-pdo_msql.ini is:
extension=pdo_mysql.so
2. thinkphp reports an error _STORAGE_WRITE_ERROR_:./Application/Runtime/Cache/Home/4e64ea6a2012f26b832b14cbc2152b28.php
It is because the operation authority of the server cache folder is not enough, that is, Runtime has no authority, delete all the cache files, and give Runtime777 authority
sudo chmod 777 Runtime or directly set 777 permissions on the outermost layer of the code base
3. The image of thinkphp verification code cannot be displayed
Lack of gd extension, install:
docker-php-ext-install gd
The following errors may be reported:
If configure fails try --with-webp-dir=<DIR> If configure fails try --with-jpeg-dir=<DIR> configure: error: png.h not found.
installation:
apt-get install libpng-dev libjpeg-dev
Execute again:
// Add freetype configuration
docker-php-ext-configure gd --enable-gd-native-ttf --with-freetype-dir=/usr/include/freetype2 --with-png-dir=/usr/include --with-jpeg-dir=/usr/include// install
docker-php-ext-install gd
php.ini adds php_gd2.so
gd library displayed in phpinfo
Note that if there is no freetype support in phpinfo’s gd library, the verification code will still not be displayed and an error will be reported:
Call to undefined function Thinkimagettftext()
If there is no freeType in the gd library, follow the steps below:
docker-php-ext-configure gd --enable-gd-native-ttf --with-freetype-dir=/usr/include/freetype2 --with-png-dir=/usr/include
Recompile:
docker-php-ext-install gd
If an error is reported:
configure: error: freetype-config not found.
Run:apt-get -y install libfreetype6-dev, And then continue to run the above command. To
With freetype in the gd library, the verification code is displayed normally:
I am a complete Docker novice but am having to maintain an existing system. The Dockerfile I am using is as below:
FROM php:5.6-apache
RUN docker-php-ext-install mysql mysqli
RUN apt-get update -y && apt-get install -y sendmail
RUN apt-get update &&
apt-get install -y
zlib1g-dev
RUN docker-php-ext-install mbstring
RUN docker-php-ext-install zip
RUN docker-php-ext-install gd
When I run ‘docker build [sitename]’ everything seems ok until I get the error:
configure: error: png.h not found.
The command '/bin/sh -c docker-php-ext-install gd' returned a non-zero code: 1
What is the cause of this error?
Answer 1
You should add the libpng-dev
package to your Dockerfile
:
FROM php:5.6-apache
RUN docker-php-ext-install mysql mysqli
RUN apt-get update -y && apt-get install -y sendmail libpng-dev
RUN apt-get update &&
apt-get install -y
zlib1g-dev
RUN docker-php-ext-install mbstring
RUN docker-php-ext-install zip
RUN docker-php-ext-install gd
Then go to directory with Dockerfile
and run:
docker build -t sitename .
It worked in my case:
Removing intermediate container f03522715567
Successfully built 9d69212196a2
Let me know if you get any errors.
EDIT:
You should see something like this:
REPOSITORY TAG IMAGE ID CREATED SIZE
sitename latest 9d69212196a2 19 minutes ago 414 MB
<none> <none> b6c69576a359 25 minutes ago 412.3 MB
EDIT2:
Just to double check everything:
Please run the docker build
command this way:
docker build -t sitename:1.0 .
(adding :1.0
should not change anything, I added it just to have additional row in docker images
output)
Then start the container:
docker run --name sitename_test -p 80:80 sitename:1.0
It should work just fine.
I assumed that apache is using standard port (80) — maybe you need to adjust that. If you have other services/containers listening on port 80 you can make your container listening on other port:
docker run --name sitename_test -p 8080:80 sitename:1.0
That will redirect the traffic from port 8080 to port 80 «inside» the container.
Normally you run container in the background. To do this add the -d
option to the docker run
command (but for testing purposes you can omit -d
to see output in the console).
If you decide to run container in the background you can check logs using docker logs sitename_test
. To follow the logs (and see updates in logs) use -f
option:
docker logs -f sitename_test
Hope that helps.
Я полный новичок в Docker, но мне нужно поддерживать существующую систему. Я использую Dockerfile, как показано ниже:
FROM php:5.6-apache
RUN docker-php-ext-install mysql mysqli
RUN apt-get update -y && apt-get install -y sendmail
RUN apt-get update &&
apt-get install -y
zlib1g-dev
RUN docker-php-ext-install mbstring
RUN docker-php-ext-install zip
RUN docker-php-ext-install gd
Когда я запускаю docker build [sitename], все выглядит нормально, пока не появится сообщение об ошибке:
configure: error: png.h not found.
The command '/bin/sh -c docker-php-ext-install gd' returned a non-zero code: 1
В чем причина этой ошибки?
4 ответа
Этот Dockerfile
работал с Php7 https://hub.docker.com/r/giapnh/php7-gd
FROM php:7-fpm
RUN docker-php-ext-install mysqli pdo pdo_mysql
RUN apt-get update -y && apt-get install -y libwebp-dev libjpeg62-turbo-dev libpng-dev libxpm-dev
libfreetype6-dev
RUN apt-get update &&
apt-get install -y
zlib1g-dev
RUN docker-php-ext-install mbstring
RUN apt-get install -y libzip-dev
RUN docker-php-ext-install zip
RUN docker-php-ext-configure gd --with-gd --with-webp-dir --with-jpeg-dir
--with-png-dir --with-zlib-dir --with-xpm-dir --with-freetype-dir
--enable-gd-native-ttf
RUN docker-php-ext-install gd
CMD ["php-fpm"]
EXPOSE 9000
12
giapnh
19 Май 2019 в 07:16
Это не относится к OP, но я обнаружил, что для тех, кто использует php:7.4-fpm-alpine
, синтаксис немного отличается
FROM php:7.4-fpm-alpine
# ... Other instructions ...
# Setup GD extension
RUN apk add --no-cache
freetype
libjpeg-turbo
libpng
freetype-dev
libjpeg-turbo-dev
libpng-dev
&& docker-php-ext-configure gd
--with-freetype=/usr/include/
# --with-png=/usr/include/ # No longer necessary as of 7.4; https://github.com/docker-library/php/pull/910#issuecomment-559383597
--with-jpeg=/usr/include/
&& docker-php-ext-install -j$(nproc) gd
&& docker-php-ext-enable gd
&& apk del --no-cache
freetype-dev
libjpeg-turbo-dev
libpng-dev
&& rm -rf /tmp/*
# ... Other instructions ...
4
phaberest
26 Апр 2020 в 12:25
К сожалению, некоторые расширения php зависят от других программ. Существует проект под названием docker-php-extension-installer, который вы можете использовать для установки расширений PHP. Он также удостоверится, что требуемые зависимости присутствуют.
Поскольку мне нужен этот внешний скрипт в нескольких контейнерах, я поместил его в общий сценарий, который я затем включаю в требуемый файл Dockerfile.
Скрипт (в .shared / scripts / install_php_extensions.sh)
#!/bin/sh
# add wget
apt-get update -yqq && apt-get -f install -yyq wget
# download helper script
wget -q -O /usr/local/bin/install-php-extensions https://raw.githubusercontent.com/mlocati/docker-php-extension-installer/master/install-php-extensions
|| (echo "Failed while downloading php extension installer!"; exit 1)
# install all required extensions
chmod uga+x /usr/local/bin/install-php-extensions && sync && install-php-extensions
gd
;
Dockerfile
# get the scripts from the build context and make sure they are executable
COPY .shared/scripts/ /tmp/scripts/
RUN chmod +x -R /tmp/scripts/
# install extensions
RUN /tmp/scripts/install_php_extensions.sh
Предупреждение. Убедитесь, что вы используете правильный контекст сборки в этом случае.
1
Hirnhamster
20 Май 2019 в 15:57
Это проблема с образом Docker для Composer. Поэтому лучше всего следовать предложению из проблемы выше и заменить строку command: install следующим образом:
composer:
...
command: install --ignore-platform-reqs
Для получения дополнительной информации перейдите по этой ссылке: https://github.com/nanoninja/docker-nginx-php- mysql / issues / 28
0
nimondo
2 Сен 2020 в 19:14