Use Docker Compose to add a database to our project.
Running PHP on an Apache server is great, but most web applications also need a database. Often, this database runs on a system separate from the web server. Docker Compose is a tool that makes it easy to configure several Docker containers at once and create a network between them. For this project, we’re going to use a Docker image that runs MySQL.
All configuration for Docker Compose is driven by a file called
docker-compose.yml. Compose looks for this file in the current directory. Let’s
add it to our website project (as a file in the my-docker-website
directory).
docker-compose.yml
version: '3'
services:
web:
image: php:7.1-apache
depends_on:
- db
volumes:
- ./:/var/www/html
ports:
- "80:80"
db:
image: mysql:5.6
environment:
- MYSQL_ROOT_PASSWORD=password
- MYSQL_DATABASE=SCHOOL
- MYSQL_USER=my_user
- MYSQL_PASSWORD=password
volumes:
- ./docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
ports:
- "3306:3306"
Let’s break that down. If you’re curious, you can also follow along in the docker-compose.yml docs.
./docker-entrypoint-initdb.d
from our host into
/docker-entrypoint-initdb.d
in our MySQL container. This is also documented
on the MySQL Docker Hub page.We’re going to want some data in our database. Download this SCHOOL.sql file to
my-docker-website/docker-entrypoint-initdb.d/SCHOOL.sql
so that it can be used
to initialize our database.
At this point, you could run docker-compose up
, but nothing interesting would
happen because our web server doesn’t interact with our database yet. In the
next lab, we’ll add some new functionality to our web server.