DEV Community

Mạnh Đạt
Mạnh Đạt

Posted on • Updated on

Creating a simple PHP service in Docker

First of all, I assume that you have docker installed. There are plenty of tutorial for that.

This is a tutorial to quickly create an image that serve a simple php service.

Folder structure

Alt Text

The public folder is where I host index.php, which echo a h1. Nothing fancy here.

vhost.conf file contains the configuration for apache2 webserver that runs inside the container. You can put it anywhere, its location really doesn't matter. I put it there to copy it to the image easily.

The Dockerfile, which contains the instructions to build the image, which we will look into next.

The Dockerfile instructions

FROM php:7.1.8-apache

COPY . /srv/app

COPY ./vhost.conf /etc/apache2/sites-available/000-default.conf

RUN chown -R www-data:www-data /srv/app \
    && a2enmod rewrite

Enter fullscreen mode Exit fullscreen mode

This is a very simple image so there aren't many instructions.
First, the FROM line tell docker to pull an already-made image called php:7.1.8-apache.

This is probably an image with apache2 and php installed.

The image I'm building inherits all the packages and software installed on the FROM image

Next, we COPY the current folder(.) to a location in the image which has the path /srv/app.

As you can see, the index.php in the container (when it is running) is /srv/app/public/html

The next COPY line copy the vhost configuration file for apache2. If you have worked with apache web server before, you'll know that by default, its settings for sites are stored at /etc/apach2/sites-available.

Finally, we RUN the command that grants rights for www-data (of the container) to the folder /srv/app (on the container) and enable mod rewrite (also, on the container).

Build the image

Finally, in the same folder, run the following command to build the image

docker build -t simple-php .
Enter fullscreen mode Exit fullscreen mode

Replace simple-php with any other name you like

You should get the message saying that image was built successfully.

Run the image

docker run --rm -p 8080:80 simple-php
Enter fullscreen mode Exit fullscreen mode

Finally, the above command run the image we have just create.
Let's try viewing the service on the browser:

Alt Text

Congratulations! You have just built and run a docker image.

Top comments (1)

Collapse
 
nashpl profile image
Krzysztof Buczynski

I always think docker can be too weak when it comes to certain PHP services which handles a lot of data.
I like the solution brought up by Docker it self and smaller PHP services fit into it very well. I recommend it to anyone who needs to develop a PHP service.