Launch WordPress Using Docker, Docker-Compose and ENV file

xr:d:DAF70A8lRQ8:14,j:8368105716694451060,t:24020408

I love using Docker-Compose because why not? Running Docker commands is painful.

Let’s compose the file:

docker-compose.yml
services:
  db:
    image: mysql:5.7
    container_name: local-db
    ports:
      - "3306:3306"
    volumes:
      - ./db/data:/var/lib/mysql
      - ./db/dump:/dump
    environment:
      MYSQL_ROOT_PASSWORD: $WORDPRESS_DB_PASSWORD
      MYSQL_DATABASE: $WORDPRESS_DB_NAME
      MYSQL_USER: $WORDPRESS_DB_USER
      MYSQL_PASSWORD: $WORDPRESS_DB_PASSWORD

  wordpress:
    container_name: local-wordpress
    volumes:
      - .:/var/www/html
    depends_on:
      - db
    image: wordpress:php7.4
    ports:
      - "80:80"
    environment:
      WORDPRESS_DB_HOST: $WORDPRESS_DB_HOST
      WORDPRESS_DB_USER: $WORDPRESS_DB_USER
      WORDPRESS_DB_PASSWORD: $WORDPRESS_DB_PASSWORD
      WORDPRESS_DB_NAME: $WORDPRESS_DB_NAME

As you can see in the file $WORDPRESS_DB_HOST, I replaced the actual value with the env variable.

Let’s now create the .env file. With my example below, I added random values.

.env
WORDPRESS_DB_HOST: 'db'
WORDPRESS_DB_USER: 'root'
WORDPRESS_DB_PASSWORD: 'root'
WORDPRESS_DB_NAME: 'wordpress'
WORDPRESS_TABLE_PREFIX: 'wp_'
WORDPRESS_AUTH_KEY: 'hi,Zm=$8!8Guue%PgH])'
WORDPRESS_SECURE_AUTH_KEY: '@wr3454545iP#xDIKou!'
WORDPRESS_LOGGED_IN_KEY: 'eHRAqn=gtOwn*ODe5rhx3ZH~c-'
WORDPRESS_NONCE_KEY: '[K*@QOTQ=_T{=]N'
WORDPRESS_AUTH_SALT: 'pogWdrwDZKWcGiq='
WORDPRESS_SECURE_AUTH_SALT: '~UbjyZ3$$)723T'
WORDPRESS_LOGGED_IN_SALT: '+d3rF1QxMQ!2'
WORDPRESS_NONCE_SALT: 'EX2'
WORDPRESS_WP_SITEURL: 'http://localhost'
WORDPRESS_WP_HOME: 'http://localhost'

Make sure the wp-config file should use the function getenv_docker

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

/** Database username */
define( 'DB_USER', getenv_docker('WORDPRESS_DB_USER', 'example username') );

/** Database password */
define( 'DB_PASSWORD', getenv_docker('WORDPRESS_DB_PASSWORD', 'example password') );

To make it work,

Bash
docker-compose --env-file .env up -d

It should pull the images and run the containers.

View gist here: https://gist.github.com/rinavillaruz/c8c64d4aec689cdadbb3a92d5cb54837

Leave a Reply