使用Docker和PHP从env文件加载环境变量 [英] Load environment variables from env file with Docker and PHP

查看:262
本文介绍了使用Docker和PHP从env文件加载环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用传递给Php应用程序的Docker文件中设置的dotenv变量?



最近尝试使用带有一组密钥的 .env文件配对的值可以在不同的配置文件中使用,但是注意到Docker + Wordpress映像不容易设置。



请参阅下面的 .env文件,该文件与docker-compose.yml位于相同的目录:

  WORDPRESS_DB_NAME = wp_xxxx 
WORDPRESS_DB_USER = xxxxxx
WORDPRESS_DB_PASSWORD = xxxxxx
WORDPRESS_DB_HOST = xxxxxxxx

此处提供了官方Wordpress图片( https://hub.docker.com/_/wordpress )说明:以下环境变量也因配置WordPress [...] WORDPRESS_DB_USER,WORDPRESS_DB_PASSWORD等而受到欢迎。



默认情况下, wp-config.php中的配置参数未替换为.env变量,这导致我通过安装composer扩展了原始Wordpress图像。让我们将文件称为 DockerWordpress.yml:

  FROM wordpress:php7.3-apache 

运行curl -sS https://getcomposer.org/installer | php---install-dir = / usr / bin --filename = composer&& chmod + x / usr / bin / composer
RUN作曲家需要vlucas / phpdotenv

在主Docker-compose.yml文件中使用,如下所示。找到服务 WordPress:

 版本: 3.1 

服务:
网络:
容器名称:网络
图像:nginx:1.15.11-alpine
卷:
-./nginx/foobar.conf:/etc/nginx/conf.d/ default.conf
-../../foobar-blog-ui/public/:/var/www/html/
端口:
-80:80
-443 :443
网络:
-foobar-wordpress-network

节点:$ b​​ $ b图片:节点:8.16.0-slim
working_dir:/ home /节点/应用程序
环境:
-NODE_ENV =开发
数量:
-../../foobar-blog-ui/:/home/node/app
-./node_modules:/home/node/app/node_modules
-./npm/.npmrc:/home/node/app/.npmrc
端口:
-8000:8000
-9000:9000
命令:bash -c apt-get update&& apt-get install -y rsync vim git libpng-dev libjpeg-dev libxi6 build-essential libgl1-mesa-glx& ;& npm安装&&退出0
d epends_on:
-wordpress
网络:
-foobar-wordpress-network

wordpress:
构建:
上下文:。
dockerfile:./Services/DockerWordpress.yml
container_name:wordpress
重新启动:失败
端口:
-8888:80
环境:
WORDPRESS_DB_HOST:$ {WORDPRESS_DB_HOST}
WORDPRESS_DB_NAME:$ {WORDPRESS_DB_NAME}
WORDPRESS_DB_USER:$ {WORDPRESS_DB_USER}
WORDPRESS_DB_PASSWORD:$ {WORDPRESS_DB_PASSWORD}
册:
- ../../foobar-wordpress-cms/:/var/www/html
-./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
-./wordpress/wp-config.php:/var/www/html/wp-config.php
depends_on:
-db
网络:
-foobar-wordpress-网络

wordpress-cli:
图片:wordpress:cli
量:
-../../foobar-wordpress-cms/:/var/www / html
-./scripts/docker-entrypoint.sh:/var/www/html/docker-entrypoint.sh
取决于:
-wordpress
-db
命令:sh -c sleep 30&&am ; ./docker-entrypoint.sh
网络:
-foobar-wordpress-network

db:
图片:mariadb:最新
端口:
-3306:3306
重新启动:故障
环境:
MYSQL_DATABASE:$ {WORDPRESS_DB_NAME}
MYSQL_USER:$ {WORDPRESS_DB_USER}
MYSQL_PASSWORD:$ { WORDPRESS_DB_PASSWORD}
#MYSQL_ROOT_HOST:$ {WORDPRESS_DB_HOST}
MYSQL_ROOT_HOST:'%'
MYSQL_RANDOM_ROOT_PASSWORD:'1'
量:
-./wordpress/database:/docker -entrypoint-initdb.d
-./mysql/my.cnf:/etc/mysql/conf.d/my.cnf
-./mysql/data:/var/lib/mysql
网络:
-foobar-wordpress-network
健康检查:
测试:[ CMD, mysqladmin,-u $ {WORDPRESS_DB_USER},-p $ { WORDPRESS_DB_PASSWORD}, ping]
间隔:60s
超时:60s
重试:3

卷:
mysql_data:
node_modules :

网络orks:
foobar-wordpress-network:
驱动程序:bridge

最后,从外部源安装到容器卷中的 wp-config.php文件,如您在前面的 docker-compose文件中所见。这是通过遵循defacto插件提供的文档来使用dotEnv变量来完成的( https://github.com/vlucas / phpdotenv )。

 <?php 

require_once( __DIR__。'./vendor/autoload.php');
(新的\Dotenv\Dotenv(__ DIR__。./../。init / Docker'))-> load();

/ **
* WordPress
的基本配置*
* wp-config.php创建脚本在
*安装过程中使用此文件。您不必使用网站,可以
*将此文件复制到 wp-config.php并填写值。
*
*该文件包含以下配置:
*
* * MySQL设置
* *密钥
* *数据库表前缀
* * ABSPATH
*
* @link https://codex.wordpress.org/Editing_wp-config.php
*
* @package WordPress
* /

// ** MySQL设置-您可以从Web主机获取此信息** //
/ ** WordPress的数据库名称* /
define( 'DB_NAME','');

/ ** MySQL数据库用户名* /
define('DB_USER',’);

/ ** MySQL数据库密码* /
define('DB_PASSWORD',’);

/ ** MySQL主机名* /
define('DB_HOST',’);

/ **用于创建数据库表的数据库字符集。 * /
define('DB_CHARSET','utf8');

/ **数据库整理类型。如有疑问,请不要更改。 * /
define('DB_COLLATE',’);

/ **#@ +
*身份验证唯一密钥和盐。
*
*将它们更改为不同的独特短语!
*您可以使用{@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org秘钥服务}生成这些文件
*您可以在以下位置进行更改任何时候使所有现有的cookie失效。这将强制所有用户必须再次登录。
*
* @ 2.6.0起
* /
define('AUTH_KEY','U(p)0EQ $ O; meOʻOe @ 1 $ t7nI?< $ = | NJ)kb + Shya21)-M2HI#/ B#e〜:@ gX +} h @ [LNE');
define('SECURE_AUTH_KEY','Qpe; 9 Ye ^ zuSozw @} 2 * f9mK〜] 7 / V1,gf [^ v4 =} @ N!$<(q2qI< 3U] kNK ^ P4b)n ; 7');
define('LOGGED_IN_KEY','R = yN?s& Ek8ncd; xuvIHU]; 2fo#piE [MbF6 63 @ aP:p1TyZmz#94(> XErht {} 6< V,');
define('NONCE_KEY','Xr〜QqP8%cjPA $]?m * -CrcjgdfA6Vao> 8C / AI6-pi_Y< rI] y = 6fKSOS6i /%4F〜Xl');
define('AUTH_SALT', '<<< 7vysQ = uPfNxyl?z = 97AyIfm〜QNn5%JI7 ^)bFW& A`V.5`W2xj + KXJY`_hV66T');
define('SECURE_AUTH_SALT','dT-4]:wh _。++< M& L6>& Eywn})wSzy + .`v6eBhl694uF(fc:yp9:?oV!PDbU(ST(');;
define('LOGGED_IN_SALT','3rPPnmKp | dUR = KX {W-TVYH7a:60P7z} $ h3jgggKJgn〜9XX`)6XuCtzMLjypztu!m');
define('NONCE_SALT','X4Aaby} g7〜R @,9 +/- mc_lfzq!* RMP + cKOgv0K [{xS73〜| k0u:zq> G.My');

/ **#@-* /

/ **
* WordPress数据库表前缀
*
*如果给每个
*一个唯一的前缀,则可以在一个数据库中进行多次安装。 ,字母和下划线!
* /
$ table_prefix ='wp_';

/ **
*对于开发人员:WordPress调试模式。 b *
*更改为true可在开发过程中显示通知
*强烈建议插件和主题开发人员在其开发环境中使用WP_DEBUG
*。 *
*有关可用于调试的其他常量的信息,
*访问食典
*
* @l墨水https://codex.wordpress.org/Debugging_in_WordPress
* /
// define('WP_DEBUG',true);
// define('WP_DEBUG_LOG',true);

/ *就这样,停止编辑!祝您发布愉快。 * /

/ ** WordPress目录的绝对路径。 * /
if(!define('ABSPATH')){
define('ABSPATH',dirname(__FILE__)。//);
}

/ **设置WordPress变量和包含的文件。 * /
require_once(ABSPATH。'wp-settings.php');

由于我使用的是作曲家和phpdotnet插件,因此我也尝试过:

  define('DB_NAME',getenv('WORDPRESS_DB_NAME')); 
...

在错误日志中,我可以读取:

  wordpress已退出,代码为4 

代码4 上方的错误是由提供环境变量引起的,该错误导致入口点脚本尝试为我们修改wp-config.php。



由于代码4 是由环境变量引起的,无论是否检查docker镜像都会返回以下内容(不会有env变量):

  [
{
Id: sha256:0d91452f5f88a168d9e85e2c4992460e2ef50d66d60c581c3ffc60b78824a416,
RepoTags:[
docker_wordpress:latest
],
RepoDigests:[],
Parent: sha256:73c390be73f955ac64e67751faba8095ed0d31a98a3eb841ea38be6a81d9bd02, $ b Comment:,
Created: 2019-09-09T22:54:10.8766881Z,
Container: 20a95e0640aa65d9c1c244cdacf0dae09 165c4da3ff19460190dce4cf4a80d8b,
ContainerConfig:{
Hostname:,
Domainname:,
User:,
AttachStdin:错误,
AttachStdout:错误,
AttachStderr:错误,
ExportPorts:{
80 / tcp:{}
},
Tty:false,
OpenStdin:false,
StdinOnce:false,
Env:[
PATH = / usr / local / sbin:/ usr / local / bin:/ usr / sbin:/ usr / bin:/ sbin:/ bin,
PHPIZE_DEPS = autoconf \t\tdpkg-dev \t\ tfile \t\tg ++ \t\tgcc \t\tlibc-dev \t\tmake \t\tpkg-config \t\tre2c,
PHP_INI_DIR = / usr / local / etc / php,
APACHE_CONFDIR = / etc / apache2,
APACHE_ENVVARS = / etc / apache2 / envvars,
PHP_EXTRA_BUILD_DEPS = apache2-dev,
PHP_EXTRA_CONFI GURE_ARGS =-with-apxs2 --disable-cgi,
PHP_CFLAGS = -fstack-protector-strong -fpic -fpie -O2,
PHP_CPPFLAGS = -fstack-protector-strong -fpic -fpie -O2,
PHP_LDFLAGS = -Wl,-O1 -Wl,-hash-style = both -pie,
GPG_KEYS = CBAF69F173A0FEA4B537F470D66C9593118BCCB6 F38252826ACD957EF380DD_FDAF4B 7.3.9,
PHP_URL = https://www.php.net/get/php-7.3.9.tar.xz/from/this/mirror,
PHP_ASC_URL = https: //www.php.net/get/php-7.3.9.tar.xz.asc/from/this/mirror\",
\"PHP_SHA256=4007f24a39822bef2805b75c625551d30be9eeed329d52eb0838fa5c1b91c1fd\"、
\"PHP_MD5=\"、$b $ b WORDPRESS_VERSION = 5.2.3,
WORDPRESS_SHA1 = 5efd37148788f3b14b295b2a9bf48a1a467aa303
],
Cmd:[
/ bin / sh,
-c,
comp oser require vlucas / phpdotenv
],
Image: sha256:73c390be73f955ac64e67751faba8095ed0d31a98a3eb841ea38be6a81d9bd02,
卷:{
/ var / www / html:{}
},
WorkingDir: / var / www / html,
Entrypoint:null,
OnBuild:null,
Label :null,
StopSignal: WINCH
},
DockerVersion: 19.03.2,
Author:,
Config:{
Hostname:,
Domainname:,
User:,
AttachStdin:false,
AttachStdout:false,
AttachStderr:false,
ExposedPorts:{
80 / tcp:{}
},
Tty :false,
OpenStdin:false,
StdinOnce:false,
Env:[
PATH = / usr / local / sbin:/ usr / local / bin:/ usr / sbin:/ usr / bin:/ sbin:/ bin,
PHPIZE_DEPS = autoconf \t\tdpkg-dev \t\tfile\t\tg ++ \t\tgcc\t\tlibc-dev \t\tmake \t\tpkg-config \t\tre2c,
PHP_INI_DIR = / usr / local / etc / php,
APACHE_CONFDIR = / etc / apache2,
APACHE_ENVVARS = / etc / apache2 / envvars,
PHP_EXTRA_BUILD_DEPS = apache2-dev,
PHP_EXTRA_CONFIGURE_ARGS =-with-apxs2 --disable-cgi,
PHP_CFLAGS = -fstack-protector-strong -fpic -fpie -O2,
PHP_CPPFLAGS = -fstack-protector-strong -fpic -fpie -O2,
PHP_LDFLAGS = -Wl,-O1 -Wl,-hash-style = both -pie,
GPG_KEYS = CBAF69F173A0FEA4B537F470D66C9593118BCC F38252826ACD957EF380D39F2F7956BC5DA04B5D,
PHP_VERSION = 7.3.9,
PHP_URL = https://www.php.net/get/php-7.3.9.tar.xz/from/this/mirror ,
PHP_ASC_URL = https://www.php.net/get/php-7.3.9.tar.xz.asc/from/this/mirror,
PHP_SHA256 = 4007f24a39822bef2805b75c625551d30be9eeed329d52eb0838fa5c1b91c1fd,
PHP_ =,
WORDPRESS_VERSION = 5.2.3,
WORDPRESS_SHA1 = 5efd37148788f3b14b295b2a9bf48a1a467aa303
],
Cmd:[
apache2-foreground
],
ArgsEscaped:是,
Image: sha256:73c390be73f955ac64e67751faba8095ed0d31a98a3eb841ea38be6a81d9bd02,
卷:{
/ var / www / html: {}
},
WorkingDir: / var / www / html,
Entrypoint:[
docker-entrypoint.sh
] ,
OnBuild:null,
Labels:null,
StopSignal: WINCH
},
Architecture: amd64,
Os: linux,
Size:530754564,
VirtualSize:530754564,
GraphDriver:{
Data:{
...
},
名称: overlay2
},
RootFS:{
类型:图层,
图层:[
...
]
},
元数据:{
LastTagTime: 2019-09-09T22:54: 10.9465719Z
}
}
]

请记住我希望文档是正确的,并且应该遵循上面的设置,所以应该尊重环境变量。

解决方案

一些说明可以帮助我找到解决方案,并希望将来对其他人有所帮助。



首先,我在尝试观察时发现的问题:




  • 第一个导致上述错误的错误是 wordpress ex代码4 的问题是wp-content.php在挂载到容器时失败,因此,其目的是允许 wordpress入口点sh脚本为我们修改文件,或者接受将执行某些操作否则,如上所述,插件phpdotenv和$ _ENV或getenv fn( https: //www.php.net/manual/zh-CN/function.getenv.php


  • 该卷已安装在Docker-compose中。 yml文件并覆盖文件,例如我们尝试将其复制到容器WORKDIR中的文件,等等


  • Docker组合上下文不允许将文件复制到其外部范围路径必须在构建上下文内




在下面,您会找到一个有效的版本(WIP ),这对我有用,它是可以遵循的默认行为的替代选择(我认为,鉴于上述要点,在考虑到所有因素的情况下进行重构)有待改进,但让我们将此与将dotenv传递给PHP保持联系,在将来对其他人会很有用。)



+++++++++ +++ docker-compose.yml ++++++++++++++++++

 版本: '3.1'

服务:
网页:
container_name:网页
图像:nginx:1.15.11-alpine
量:
- ./nginx/foobar.conf:/etc/nginx/conf.d/default.conf
-../../foobar-blog-ui/public/:/var/www/html/
端口:
-80:80
-443:443
网络:
-foobar-wordpress-network

节点:$ b​​ $ b image :node:8.16.0-slim
working_dir:/ home / node / app
环境:
-NODE_ENV =开发项目
量:
-../ .. / foobar-blog-ui /:/ home / node / app
-./node_modules:/home/node/app/node_modules
-./npm/.npmrc:/home/node/app/ .npmrc
端口:
-8000:8000
-9000:9000
命令:bash -c apt-get update && apt-get install -y rsync vim git libpng-dev libjpeg-dev libxi6 build-essential libgl1-mesa-glx&& npm安装&&退出0
取决于:
-wordpress
网络:
-foobar-wordpress-network

wordpress:
构建:
上下文:../../
dockerfile:./.init/Docker/Services/DockerWordpress.yml
container_name:wordpress
重新启动:失败
端口:
-8888:80
取决于:
-db
网络:
-foobar-wordpress-network

wordpress-cli:
图片:wordpress:cli
卷:
-../../foobar-wordpress-cms/:/var/www/html
-./scripts/docker-entrypoint.sh :/var/www/html/docker-entrypoint.sh
取决于:
-wordpress
-db
命令:sh -c sleep 30& ./docker-entrypoint.sh
网络:
-foobar-wordpress-network

数量:
node_modules:

网络:
foobar-wordpress-network:
驱动程序:桥

++++ ++++++++ dockerfile ++++++++++++++++++

 从wordpress:php7.3-apache 

WORKDIR / var / www / html /

COPY ./.init/Docker/.env。
COPY ./foobar -wordpress-cms。
COPY ./.init/Docker/php/uploads.ini /usr/local/etc/php/conf.d/uploads.ini
COPY ./.init/Docker/ wordpress / wp-config.php ./wp-config.php

RUN curl -sS https://getcomposer.org/installer | php---install-dir = / usr / bin- -filename = composer& champ + x / usr / bin / composer
RUN作曲家需要vlucas / phpdotenv
RUN ls -la

以下文章也有帮助( https://vsupalov.com/docker-a rg-env-variable-guide /#the-dot-env-file-env )。


How to use dotenv variables set in the Docker file, passed to a Php application?

Recently tried to use a ".env" file with a set of key paired values to use across different configuration files, but noticed that Docker + the Wordpress image is not easy to setup. While quite trivial to set up in node, etc.

See the ".env" file below that sits same dir as the docker-compose.yml:

WORDPRESS_DB_NAME=wp_xxxx
WORDPRESS_DB_USER=xxxxxx
WORDPRESS_DB_PASSWORD=xxxxxx
WORDPRESS_DB_HOST=xxxxxxxx

The official Wordpress image available here ( https://hub.docker.com/_/wordpress ) documents that "The following environment variables are also honoured for configuring your WordPress [...] WORDPRESS_DB_USER, WORDPRESS_DB_PASSWORD, etc".

By default the Configuration parameters in the "wp-config.php" are not replaced by the .env variables, which lead me to extend the original Wordpress image by installing composer. Let's call the file bellow "DockerWordpress.yml":

FROM wordpress:php7.3-apache

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/bin --filename=composer && chmod +x /usr/bin/composer 
RUN composer require vlucas/phpdotenv

That is used in the main Docker-compose.yml file, as we can see below. Find the service "Wordpress":

version: '3.1'

services:
  web:
    container_name: web
    image: nginx:1.15.11-alpine
    volumes:
      - ./nginx/foobar.conf:/etc/nginx/conf.d/default.conf
      - ../../foobar-blog-ui/public/:/var/www/html/
    ports:
      - 80:80
      - 443:443
    networks:
      - foobar-wordpress-network

  node:
    image: node:8.16.0-slim
    working_dir: /home/node/app
    environment:
      - NODE_ENV=development
    volumes:
      - ../../foobar-blog-ui/:/home/node/app
      - ./node_modules:/home/node/app/node_modules
      - ./npm/.npmrc:/home/node/app/.npmrc
    ports:
     - 8000:8000
     - 9000:9000
    command: bash -c "apt-get update && apt-get install -y rsync vim git libpng-dev libjpeg-dev libxi6 build-essential libgl1-mesa-glx && npm install && exit 0"
    depends_on:
      - wordpress
    networks:
      - foobar-wordpress-network

  wordpress:
    build:
      context: .
      dockerfile: ./Services/DockerWordpress.yml
    container_name: wordpress
    restart: on-failure
    ports:
      - 8888:80
    environment:
      WORDPRESS_DB_HOST: ${WORDPRESS_DB_HOST}
      WORDPRESS_DB_NAME: ${WORDPRESS_DB_NAME}
      WORDPRESS_DB_USER: ${WORDPRESS_DB_USER}
      WORDPRESS_DB_PASSWORD: ${WORDPRESS_DB_PASSWORD}
    volumes:
      - ../../foobar-wordpress-cms/:/var/www/html
      - ./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
      - ./wordpress/wp-config.php:/var/www/html/wp-config.php
    depends_on:
      - db
    networks:
      - foobar-wordpress-network

  wordpress-cli:
    image: wordpress:cli
    volumes:
      - ../../foobar-wordpress-cms/:/var/www/html
      - ./scripts/docker-entrypoint.sh:/var/www/html/docker-entrypoint.sh
    depends_on:
      - wordpress
      - db
    command: sh -c "sleep 30 && ./docker-entrypoint.sh"
    networks:
      - foobar-wordpress-network

  db:
    image: mariadb:latest
    ports:
      - 3306:3306
    restart: on-failure
    environment:
      MYSQL_DATABASE: ${WORDPRESS_DB_NAME}
      MYSQL_USER: ${WORDPRESS_DB_USER}
      MYSQL_PASSWORD: ${WORDPRESS_DB_PASSWORD}
    #   MYSQL_ROOT_HOST: ${WORDPRESS_DB_HOST}
      MYSQL_ROOT_HOST: '%'
      MYSQL_RANDOM_ROOT_PASSWORD: '1'
    volumes:
      - ./wordpress/database:/docker-entrypoint-initdb.d
      - ./mysql/my.cnf:/etc/mysql/conf.d/my.cnf"
      - ./mysql/data:/var/lib/mysql
    networks:
      - foobar-wordpress-network
    healthcheck:
        test: ["CMD", "mysqladmin", "-u${WORDPRESS_DB_USER}", "-p${WORDPRESS_DB_PASSWORD}", "ping"]
        interval: 60s
        timeout: 60s
        retries: 3

volumes:
  mysql_data:
  node_modules:

networks:
  foobar-wordpress-network:
      driver: bridge

Finally, the "wp-config.php" file that is mounted from an external source into the container volume, as you can see in the previous "docker-compose" file. This is done by following the documentation provided by the defacto plugin to use dotEnv variables ( https://github.com/vlucas/phpdotenv ) in the Php community.

<?php

require_once(__DIR__ . './vendor/autoload.php');
(new \Dotenv\Dotenv(__DIR__ . '/../.init/Docker'))->load();

/**
 * The base configuration for WordPress
 *
 * The wp-config.php creation script uses this file during the
 * installation. You don't have to use the web site, you can
 * copy this file to "wp-config.php" and fill in the values.
 *
 * This file contains the following configurations:
 *
 * * MySQL settings
 * * Secret keys
 * * Database table prefix
 * * ABSPATH
 *
 * @link https://codex.wordpress.org/Editing_wp-config.php
 *
 * @package WordPress
 */

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', '');

/** MySQL database username */
define( 'DB_USER', '');

/** MySQL database password */
define( 'DB_PASSWORD', '');

/** MySQL hostname */
define( 'DB_HOST', '');

/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '');

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define( 'AUTH_KEY',         'U(p)0EQ$O;meL`Oe@1$t7nI?<$=|NJ)kb+Shya21)-M2HI#/B#e~:@gX+}h@[LNE' );
define( 'SECURE_AUTH_KEY',  'Qpe;9 Ye^zuSozw@}2*f9mK~]7/V1,gf[^v4=}@ N!$<(q2qI<3U]kNK^P4b)n;7' );
define( 'LOGGED_IN_KEY',    'R=yN?s&Ek8ncd;xuvIHU];2fo#piE[MbF6 63@aP:p1TyZmz#94(>XErht{}6<V,' );
define( 'NONCE_KEY',        'Xr~QqP8%cjPA$] ?m*-CrcjgdfA6Vao>8C/AI6-pi_Y<rI]y=6fKSOS6i/%4F~Xl' );
define( 'AUTH_SALT',        '<<7vysQ=uPfNxyl? z=97AyIfm~QNn5%JI7^)bFW&;A`V.5`W2xj+KXJY`_hV66T' );
define( 'SECURE_AUTH_SALT', 'dT-4]:wh_.++<M&L6>&Eywn})wSzy+.`v6eBhl694uF(fc:yp9:?oV! PDbU(ST(' );
define( 'LOGGED_IN_SALT',   '3rPPnmKp|dUR=KX{W-TVYH7a:60P7z}$h3jgggKJgn~9XX`)6XuCtzMLjypztu!m' );
define( 'NONCE_SALT',       'X4aAby}iQOenS$2g7~R@,9+/-mc_lfzq!*RMP+cKOgv0K[{xS73~|k0u:zq>G.My' );

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix = 'wp_';

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the Codex.
 *
 * @link https://codex.wordpress.org/Debugging_in_WordPress
 */
// define( 'WP_DEBUG', true );
// define( 'WP_DEBUG_LOG', true );

/* That's all, stop editing! Happy publishing. */

/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
    define( 'ABSPATH', dirname( __FILE__ ) . '/' );
}

/** Sets up WordPress vars and included files. */
require_once( ABSPATH . 'wp-settings.php' );

Since I'm using composer and the phpdotnet plugin, I've also tried:

define( 'DB_NAME', getenv('WORDPRESS_DB_NAME'));
...

In the error log, I can read:

wordpress exited with code 4

The error above code 4 is caused by providing "environment variables", that causes the entrypoint script to try to modify the wp-config.php for us.

Since the code 4 is caused by the environment variables, with or without the inspect docker image returns the following (does not have env variables):

[
    {
        "Id": "sha256:0d91452f5f88a168d9e85e2c4992460e2ef50d66d60c581c3ffc60b78824a416",
        "RepoTags": [
            "docker_wordpress:latest"
        ],
        "RepoDigests": [],
        "Parent": "sha256:73c390be73f955ac64e67751faba8095ed0d31a98a3eb841ea38be6a81d9bd02",
        "Comment": "",
        "Created": "2019-09-09T22:54:10.8766881Z",
        "Container": "20a95e0640aa65d9c1c244cdacf0dae09165c4da3ff19460190dce4cf4a80d8b",
        "ContainerConfig": {
            "Hostname": "",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "PHPIZE_DEPS=autoconf \t\tdpkg-dev \t\tfile \t\tg++ \t\tgcc \t\tlibc-dev \t\tmake \t\tpkg-config \t\tre2c",
                "PHP_INI_DIR=/usr/local/etc/php",
                "APACHE_CONFDIR=/etc/apache2",
                "APACHE_ENVVARS=/etc/apache2/envvars",
                "PHP_EXTRA_BUILD_DEPS=apache2-dev",
                "PHP_EXTRA_CONFIGURE_ARGS=--with-apxs2 --disable-cgi",
                "PHP_CFLAGS=-fstack-protector-strong -fpic -fpie -O2",
                "PHP_CPPFLAGS=-fstack-protector-strong -fpic -fpie -O2",
                "PHP_LDFLAGS=-Wl,-O1 -Wl,--hash-style=both -pie",
                "GPG_KEYS=CBAF69F173A0FEA4B537F470D66C9593118BCCB6 F38252826ACD957EF380D39F2F7956BC5DA04B5D",
                "PHP_VERSION=7.3.9",
                "PHP_URL=https://www.php.net/get/php-7.3.9.tar.xz/from/this/mirror",
                "PHP_ASC_URL=https://www.php.net/get/php-7.3.9.tar.xz.asc/from/this/mirror",
                "PHP_SHA256=4007f24a39822bef2805b75c625551d30be9eeed329d52eb0838fa5c1b91c1fd",
                "PHP_MD5=",
                "WORDPRESS_VERSION=5.2.3",
                "WORDPRESS_SHA1=5efd37148788f3b14b295b2a9bf48a1a467aa303"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "composer require vlucas/phpdotenv"
            ],
            "Image": "sha256:73c390be73f955ac64e67751faba8095ed0d31a98a3eb841ea38be6a81d9bd02",
            "Volumes": {
                "/var/www/html": {}
            },
            "WorkingDir": "/var/www/html",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": null,
            "StopSignal": "WINCH"
        },
        "DockerVersion": "19.03.2",
        "Author": "",
        "Config": {
            "Hostname": "",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "PHPIZE_DEPS=autoconf \t\tdpkg-dev \t\tfile \t\tg++ \t\tgcc \t\tlibc-dev \t\tmake \t\tpkg-config \t\tre2c",
                "PHP_INI_DIR=/usr/local/etc/php",
                "APACHE_CONFDIR=/etc/apache2",
                "APACHE_ENVVARS=/etc/apache2/envvars",
                "PHP_EXTRA_BUILD_DEPS=apache2-dev",
                "PHP_EXTRA_CONFIGURE_ARGS=--with-apxs2 --disable-cgi",
                "PHP_CFLAGS=-fstack-protector-strong -fpic -fpie -O2",
                "PHP_CPPFLAGS=-fstack-protector-strong -fpic -fpie -O2",
                "PHP_LDFLAGS=-Wl,-O1 -Wl,--hash-style=both -pie",
                "GPG_KEYS=CBAF69F173A0FEA4B537F470D66C9593118BCCB6 F38252826ACD957EF380D39F2F7956BC5DA04B5D",
                "PHP_VERSION=7.3.9",
                "PHP_URL=https://www.php.net/get/php-7.3.9.tar.xz/from/this/mirror",
                "PHP_ASC_URL=https://www.php.net/get/php-7.3.9.tar.xz.asc/from/this/mirror",
                "PHP_SHA256=4007f24a39822bef2805b75c625551d30be9eeed329d52eb0838fa5c1b91c1fd",
                "PHP_MD5=",
                "WORDPRESS_VERSION=5.2.3",
                "WORDPRESS_SHA1=5efd37148788f3b14b295b2a9bf48a1a467aa303"
            ],
            "Cmd": [
                "apache2-foreground"
            ],
            "ArgsEscaped": true,
            "Image": "sha256:73c390be73f955ac64e67751faba8095ed0d31a98a3eb841ea38be6a81d9bd02",
            "Volumes": {
                "/var/www/html": {}
            },
            "WorkingDir": "/var/www/html",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": null,
            "StopSignal": "WINCH"
        },
        "Architecture": "amd64",
        "Os": "linux",
        "Size": 530754564,
        "VirtualSize": 530754564,
        "GraphDriver": {
            "Data": {
                ...
            },
            "Name": "overlay2"
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                ...
            ]
        },
        "Metadata": {
            "LastTagTime": "2019-09-09T22:54:10.9465719Z"
        }
    }
]

Have in mind that I expect that the documentation is correct and that the setup above, that the environment variables should be honoured.

解决方案

Here're a few notes that helped me found the solution, and hope it helps someone else in the future.

First the issues I found while trying and seeing:

  • the first one that caused the error exposed above as wordpress exited with code 4 is that wp-content.php fails when mounted into the container, so either the intention is to allow the "wordpress" entrypoint sh script to modify the file for us or accept will do something else, as tried above, the plugin phpdotenv and $_ENV or getenv fn (https://www.php.net/manual/en/function.getenv.php)

  • the volume is mounted in the Docker-compose.yml file and overwrites files such as the ones we try to COPY into the container WORKDIR, etc

  • The Docker-compose context doesn't allow copying files outside its scope "The path must be inside the context of the build"

Below you'll find a working version (WIP), that worked for me, as an alternative to the default behaviour that, as stated should be honoured (I believe that refactoring, given the points mentioned above, taking into consideration all, this can be improved, but let's keep this related with passing dotenv to PHP, should be useful for someone else in the future).

++++++++++++ docker-compose.yml ++++++++++++++++

version: '3.1'

services:
  web:
    container_name: web
    image: nginx:1.15.11-alpine
    volumes:
      - ./nginx/foobar.conf:/etc/nginx/conf.d/default.conf
      - ../../foobar-blog-ui/public/:/var/www/html/
    ports:
      - 80:80
      - 443:443
    networks:
      - foobar-wordpress-network

  node:
    image: node:8.16.0-slim
    working_dir: /home/node/app
    environment:
      - NODE_ENV=development
    volumes:
      - ../../foobar-blog-ui/:/home/node/app
      - ./node_modules:/home/node/app/node_modules
      - ./npm/.npmrc:/home/node/app/.npmrc
    ports:
     - 8000:8000
     - 9000:9000
    command: bash -c "apt-get update && apt-get install -y rsync vim git libpng-dev libjpeg-dev libxi6 build-essential libgl1-mesa-glx && npm install && exit 0"
    depends_on:
      - wordpress
    networks:
      - foobar-wordpress-network

  wordpress:
    build:
      context: ../../
      dockerfile: ./.init/Docker/Services/DockerWordpress.yml
    container_name: wordpress
    restart: on-failure
    ports:
      - 8888:80
    depends_on:
      - db
    networks:
      - foobar-wordpress-network

  wordpress-cli:
    image: wordpress:cli
    volumes:
      - ../../foobar-wordpress-cms/:/var/www/html
      - ./scripts/docker-entrypoint.sh:/var/www/html/docker-entrypoint.sh
    depends_on:
      - wordpress
      - db
    command: sh -c "sleep 30 && ./docker-entrypoint.sh"
    networks:
      - foobar-wordpress-network

volumes:
  node_modules:

networks:
  foobar-wordpress-network:
      driver: bridge

++++++++++++ dockerfile ++++++++++++++++

FROM wordpress:php7.3-apache

WORKDIR /var/www/html/

COPY ./.init/Docker/.env .
COPY ./foobar-wordpress-cms .
COPY ./.init/Docker/php/uploads.ini /usr/local/etc/php/conf.d/uploads.ini
COPY ./.init/Docker/wordpress/wp-config.php ./wp-config.php

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/bin --filename=composer && chmod +x /usr/bin/composer 
RUN composer require vlucas/phpdotenv
RUN ls -la

The following article also helped ( https://vsupalov.com/docker-arg-env-variable-guide/#the-dot-env-file-env ).

这篇关于使用Docker和PHP从env文件加载环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆