PHP7 with Docker

2017-06-11

I wanted to play around a bit with PHP 7 and it seemed a good time to test this docker thingy as well.

In principle, a docker container isolates processes with different kernel namespaces and blends file systems - you can use these features without docker, if you need to.

After installing docker-ce, I looked around for a container with PHP 7. Since docker works by layering file systems on top of each other, starting with an already big base image will only increase the space needed. As it turns out, the official PHP repository has some smallish images based on alpine linux.

So, I picked an image with apache - just to see, if it works. The Idea is to encapsulate every "microservice" into a single docker container. One for running a webserver, one for running PHP and so on.

To download an image from the docker hub use pull: docker pull php:7.1-apache

After that docker images should show you the image - 391MB isn't really small, but without apache, 7.1-alpine is only ~57MB.

To make an container from this image, we need docker run. Because there are some parameters, it might be easier to make a small bash script. My test project looks like this:

├── htdocs
│   └── index.php
└── run.sh

index.php

<?php
    phpinfo();

run.sh

#!/bin/bash

docker run \
    --rm \
    --name apache-php7 \
    -p 80:80 \
    -v "$PWD/htdocs":/var/www/html \
    -d \
    php:7.1-apache

Now, what does that all mean?
--rm will remove the container, if it exists. This is important since with...
--name apache-php7 ...it gets a name that needs to be unique.
-p 80:80 connects port 80 outside to port 80 inside the container.
-v "$PWD/htdocs":/var/www/html mounts the volume into the container. If a container saves files into a directory that isn't mounted somewhere outside and you destroy the container, you will lose that data.
-d run the container in the background.
How do you know which port/volume are available? That should be documented in the readme of the image, I guess.

After starting the container, it will be listed as running: docker ps -a and you should get a web page with PHP 7 when you navigate to localhost. Stopping and restarting the container is done with docker stop apache-php7 and docker start apache-php7.

How to build Images with Dockerfiles is a topic for another day...


Blogarchiv