1

I'm trying to run a wordpress site on kubernetes, but as it is behind the nginx ingress, it needs the line $_SERVER['HTTPS']='on'; in wp-config.php, as seen in here.

When not setting any env variables the docker image uses the wp-config.php provided by me, so I could test that the above line fixes my problem.

Following the documentation, I set all my variables as you can see bellow, however, the WORDPRESS_CONFIG_EXTRA env variable does not seems to be applied to the config file. It should be noted that the variable is set and can be accessed inside the pod with echo $WORDPRESS_CONFIG_EXTRA

I'm also using an external mysql database, with an already populated db on it that the wordpress pod uses.

If this post is not old, the website should be online here, but not for long as the cluster is expensive. You can check that some resources are being loaded with http, when https should be used. That line would fix this.

The Dockerfile for my custom image (wp-config.php is ignored in .dockerignore):

FROM wordpress:php7.1-apache

COPY . /usr/src/wordpress/

Here is my deployment.yaml:

apiVersion: v1
kind: Service
metadata:
  name: black
spec:
  ports:
  - port: 80
    targetPort: 80
  selector:
    app: wordpress
    tier: frontend
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: black-pv-claim
  labels:
    app: wordpress
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
---
apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
  name: black
  labels:
    app: wordpress
spec:
  selector:
    matchLabels:
      app: wordpress
      tier: frontend
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: wordpress
        tier: frontend
    spec:
      containers:
      - image: setti7/asc-theme:0.1.6
        name: black
        imagePullPolicy: Always
        env:
        - name: WORDPRESS_TABLE_PREFIX
          value: wpsy_
        - name: WORDPRESS_DB_NAME
          value: black
        - name: WORDPRESS_DB_USER
          value: black_user
        - name: WORDPRESS_DB_HOST
          value: wordpress-mysql
        - name: WORDPRESS_DB_PASSWORD
          value: blackpassword
        - name: WORDPRESS_CONFIG_EXTRA
          value: |
            define('FORCE_SSL_ADMIN', true);
            if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
            $_SERVER['HTTPS']='on';
        ports:
        - containerPort: 80
          name: black
        volumeMounts:
        - name: black-persistent-storage
          mountPath: /var/www/html
      volumes:
      - name: black-persistent-storage
        persistentVolumeClaim:
          claimName: black-pv-claim

Here is the wp-config.php generated inside the pod, that you can see does not contain the lines given by WORDPRESS_CONFIG_EXTRA:

<?php
/**
 * As configurações básicas do WordPress
 *
 * O script de criação wp-config.php usa esse arquivo durante a instalação.
 * Você não precisa usar o site, você pode copiar este arquivo
 * para "wp-config.php" e preencher os valores.
 *
 * Este arquivo contém as seguintes configurações:
 *
 * * Configurações do MySQL
 * * Chaves secretas
 * * Prefixo do banco de dados
 * * ABSPATH
 *
 * @link https://codex.wordpress.org/pt-br:Editando_wp-config.php
 *
 * @package WordPress
 */

// ** Configurações do MySQL - Você pode pegar estas informações com o serviço de hospedagem ** //
/** O nome do banco de dados do WordPress */
define('DB_NAME', 'black');

/** Usuário do banco de dados MySQL */
define('DB_USER', 'black_user');

/** Senha do banco de dados MySQL */
define('DB_PASSWORD', 'blackpassword');

/** Nome do host do MySQL */
define('DB_HOST', 'wordpress-mysql');

/** Charset do banco de dados a ser usado na criação das tabelas. */
define('DB_CHARSET', 'utf8');

/** O tipo de Collate do banco de dados. Não altere isso se tiver dúvidas. */
define('DB_COLLATE', '');

/**#@+
 * Chaves únicas de autenticação e salts.
 *
 * Altere cada chave para um frase única!
 * Você pode gerá-las
 * usando o {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org
 * secret-key service}
 * Você pode alterá-las a qualquer momento para invalidar quaisquer
 * cookies existentes. Isto irá forçar todos os
 * usuários a fazerem login novamente.
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         'coloque a sua frase única aqui');
define('SECURE_AUTH_KEY',  'coloque a sua frase única aqui');
define('LOGGED_IN_KEY',    'coloque a sua frase única aqui');
define('NONCE_KEY',        'coloque a sua frase única aqui');
define('AUTH_SALT',        'coloque a sua frase única aqui');
define('SECURE_AUTH_SALT', 'coloque a sua frase única aqui');
define('LOGGED_IN_SALT',   'coloque a sua frase única aqui');
define('NONCE_SALT',       'coloque a sua frase única aqui');

/**#@-*/

/**
 * Prefixo da tabela do banco de dados do WordPress.
 *
 * Você pode ter várias instalações em um único banco de dados se você der
 * um prefixo único para cada um. Somente números, letras e sublinhados!
 */
$table_prefix = 'wpsy_';

/**
 * Para desenvolvedores: Modo de debug do WordPress.
 *
 * Altere isto para true para ativar a exibição de avisos
 * durante o desenvolvimento. É altamente recomendável que os
 * desenvolvedores de plugins e temas usem o WP_DEBUG
 * em seus ambientes de desenvolvimento.
 *
 * Para informações sobre outras constantes que podem ser utilizadas
 * para depuração, visite o Codex.
 *
 * @link https://codex.wordpress.org/pt-br:Depura%C3%A7%C3%A3o_no_WordPress
 */
define('WP_DEBUG', false);

/* Isto é tudo, pode parar de editar! :) */

/** Caminho absoluto para o diretório WordPress. */
if ( !defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . '/');

/** Configura as variáveis e arquivos do WordPress. */
require_once(ABSPATH . 'wp-settings.php');
New contributor
Setti7 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1

This is still not well known issue, but already resolved.

It’s important to know that any change in WORDPRESS_CONFIG_EXTRA won’t be added to wp-config.php after the container volume is created. Check this issue Changes to WORDPRESS_CONFIG_EXTRA ignored unless wp-config.php is deleted.

A way to work around this is to remove the wp-config.php file after any update to WORDPRESS_CONFIG_EXTRA or remove the volume and allow it to recreate it.

Also take a look at docker-entrypoint.sh example part on how others achieve it.

if [ ! -e wp-config.php ]; then
    awk '
        /^\/\*.*stop editing.*\*\/$/ && c == 0 {
            c = 1
            system("cat")
            if (ENVIRON["WORDPRESS_CONFIG_EXTRA"]) {
                print "// WORDPRESS_CONFIG_EXTRA"
                print ENVIRON["WORDPRESS_CONFIG_EXTRA"] "\n"
            }
        }
        { print }
    ' wp-config-sample.php > wp-config.php <<'EOPHP'

What else I can add here.. Probably if I did the same - I would pass WORDPRESS_CONFIG_EXTRA variable in entrypoint script and not in deployment. You can find a lot of examples like this

  • After suffering to change this and a lot of errors, I solved the issue by simply pasting what I wanted into the wp-config-sample.php file, as it is used as a base model for the wp-config.php. By the way, did you know already how to solve this issue or you googled my question? As I'm still learning it is nice to know how you got to this solution. Thanks for your help! – Setti7 2 days ago

Your Answer

Setti7 is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.