Home  >  Article  >  Backend Development  >  Docker-based PHP development environment

Docker-based PHP development environment

WBOY
WBOYOriginal
2016-08-10 08:48:39986browse

Reprinted from: http://dockone.io/article/117

【Editor's Note】The author of this article is Geoffrey, he is a PHP web developer who likes DevOps and Docker. This article mainly introduces how to use Docker to build a PHP development environment. The author also discusses whether to use a single container or multiple containers to build a development environment based on Docker, and what are the pros and cons of each. Recommended for PHP developers to read.
Many developers now use Vagrant to manage their virtual machine development environments. Vagrant is really cool, but it also has many shortcomings (the main one is that it takes up too many resources). After the emergence of container technology, Docker and more Docker-like technologies, solving this problem has become simple.
Disclaimer
Due to the way boot2docker works, the methods described in this article may not work properly in your environment. If you need to share a folder to a Docker container in a non-Linux environment, you need to pay attention to more additional details. I will write a follow-up article specifically to introduce the actual problems encountered.
What is a good development environment?
First of all, we have to know what is a good development environment. For me, a good development environment needs to have the following characteristics:
It can be used at will. I must be able to delete and create new environments at will.
Quick start. When I want to work with it, it works immediately.
Easy to update. Things move and change very quickly in our industry, and it must be easy for me to update my development environment to new software versions.
Docker supports all of the above features and even more. You can destroy and rebuild containers almost instantly, and updating your environment only requires rebuilding the image you are currently using.
What is a PHP development environment?
Currently, web applications are complex, and a PHP development environment requires a lot of things. In order to ensure the simplicity of the environment, various restrictions need to be made.
We use Nginx, PHP5-FPM, and MySQL to run the Synmfony project this time. Since running the command line in a container is more complicated, I will leave this aspect to the next blog.
Pet and Cattle
Another key point we want to discuss is: should we deploy the development environment in multiple containers or in a single container. Both methods have their own advantages:
A single container is easy to distribute and maintain. Because they are independent, everything runs in the same container, which is like a virtual machine. But this also means that when you want to upgrade something in it (such as a new version of PHP), you need to rebuild the entire container.
Multiple containers can provide better modularity when adding components. Because each container contains part of the stack: Web, PHP, MySQL, etc., each service can be scaled or added independently without having to rebuild everything.
Because I am lazy and I need to put something else on my notebook, so here we only introduce the method of a single container.
Initialize the project
The first thing to do is to initialize a new Symfony project. The recommended method is to use composer's create-project command. It would have been possible to install composer on the workstation, but that would have been too simple. This time we use it via Docker.
I previously posted an article about Docker commands: make docker commands (ok, I lied, I originally wrote it in this article, and then thought it would be better to separate it).
Anyway, you can read it. Next, if there is no composer command yet, you can create your own composer alias.
$ alias composer="docker run -i -t -v $PWD:/srv ubermuda/composer"
Now you can initialize the Symfony project:
$ composer create-project symfony/framwork-standard-edition SomeProject
Awesome ! Now comes some real work. (Omitting a bunch of balabla that the blogger amused himself with....Original text: Awesome. Give yourself a high-five, get a cup of coffee or whatever is your liquid drug of choice, and get ready for the real work. )
Container
It is quite easy to build a self-sufficient container that runs a standard Symfony project. You only need to install the commonly used Nginx, PHP5-FPM and MySQL-Server, and then throw in the pre-prepared Nginx virtual host configuration file , then copy some configuration files and you're done.
The source code of this container can be found in the ubermuda/docker-symfony repository on GitHub. Dockerfile is the configuration file used by Docker to build images. Let’s take a look:
FROM debian:wheezy
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update -y
RUN apt-get install -y nginx php5-fpm php5-mysqlnd php5 -cli mysql-server supervisor
RUN sed -e 's/;daemonize = yes/daemonize = no/' -i /etc/php5/fpm/php-fpm.conf
RUN sed -e 's/;listen.owner /listen.owner/' -i /etc/php5/fpm/pool.d/www.conf
RUN sed -e 's/;listen.group/listen.group/' -i /etc/php5/fpm/pool .d/www.conf
RUN echo "ndaemon off;" >> /etc/nginx/nginx.conf
ADD vhost.conf /etc/nginx/sites-available/default
ADD supervisor.conf /etc/supervisor /conf.d/supervisor.conf
ADD init.sh /init.sh
EXPOSE 80 3306
VOLUME ["/srv"]
WORKDIR /srv
CMD ["/usr/bin/supervisord"]
We extend debian :wheezy starts with this base image, and then configures Nginx and PHP5-FPM through a series of sed commands.
RUN sed -e 's/;daemonize = yes/daemonize = no/' -i /etc/php5/fpm/php-fpm.conf
RUN sed -e 's/;listen.owner/listen.owner/' -i /etc/php5/fpm/pool.d/www.conf
RUN sed -e 's/;listen.group/listen.group/' -i /etc/php5/fpm/pool.d/www.conf
RUN echo "ndaemon off;" >> /etc/nginx/nginx.conf
We have to do two things here. First configure PHP5-FPM and Nginx to run in the foreground so supervisord can track them.
Then, configure PHP5-FPM to run the Web-Server as the specified user and handle file permissions.
Next, you need to install a set of configuration files. The first is the Nginx virtual host configuration file vhost.conf:
server {
listen 80;
server_name _;
access_log /var/log/nginx/access.log;
error_log /var /log/nginx/error.log;
root /srv/web;
index app_dev.php;
location / {
try_files $uri $uri/ /app_dev.php?$query_string;
}
location ~ [^/] ... $_placeholder variable), and configure the document root to /svr/web, we will deploy the application under /srv, and the rest is the standard Mginx + PHP5-FPM configuration.
Because a container To run only one program at a time, we need supervisord (or any other process manager, but I prefer supervisord). Fortunately, this process manager will spawn all the processes we need! The following is a short section of supervisord configuration:
[supervisord]
nodaemon=true
[program:nginx]
command=/usr/sbin/nginx
[program:php5-fpm]
command=/usr/sbin/php5-fpm
[program:mysql]
command=/usr/bin/mysqld_safe
[program:init]
command=/init.sh
autorestart=false
redirect_stderr=true
redirect_stdout=/srv/app/logs/init.log
What we need to do here is to define all the services and add a special program: init process. It is not an actual service, but an original way of running the startup script.
The problem with this startup script is that it usually needs to start some services first. For example, you may want to initialize some database tables, but only if you run MySQL first. A possible solution is to start MySQL in the startup script and then initialize the tables. Then, in order to prevent it from affecting supervisord's process management, you need to Stop MySQL and finally start supervisord.
Such a script looks similar to the following:
/etc/init.d/mysql start
app/console doctrine:schema:update --force
/etc/init.d/mysql stop
exec /usr/bin/supervisord
It looks ugly. Let’s try another method and let the supervisor run it and never restart it.
The actual init.sh script is as follows:
#!/bin/bash
RET=1
while [[ RET -ne 0 ]]; do
sleep 1;
mysql -e 'exit' > /dev/null 2> ;&1; RET=$?
done
DB_NAME=${DB_NAME:-symfony}
mysqladmin -u root create $DB_NAME
if [ -n "$INIT" ]; then
/srv/$INIT
fi
Script first Wait for MySQL to start, then create the DB based on the environment variable DB_NAME, which defaults to symfony, then look for the script to run in the INIT environment variable and try to run it. The end of this article explains how to use these environment variables.
Build and run the image
Everything is ready, all you need is the east wind. We also need to build the Symfony Docker image, using the docker build command:
$ cd docker-symfony
$ docker build -t symfony .
Now, you can use it to run your Symfony project:
$ cd SomeProject
$ docker run - i -t -P -v $PWD:/srv symfony
Let’s take a look at what this series of options does:
-i starts interactive mode, that is, STDIO (standard input and output) is connected to on your current terminal. This is useful when you want to receive logs or send signals to a process.
-t creates a virtual TTY for the container. It is a good friend of -i and is usually used together.
-P tells the Docker daemon to publish all specified ports, in this case port 80.
-v $PWD:/srv Mount the current directory to the container’s /srv directory. Mounting a directory makes the directory contents available to the target mount point.
Now you still remember the DB_NAME and INIT environment variables mentioned before, why are they used: to customize your environment. Basically you can set environment variables in the container through the -e option of docker run, and the startup script will get the environment variables. Therefore, if your DB is named some_project_dev, you can run the container like this:
$ docker run -i - t -P -v $PWD:/srv -e DB_NAME=some_project_dev symfony
INIT environment variable is more powerful, it allows you to run specified scripts at startup.For example, you have a bin/setup script that runs the composer install command and sets the database schema:
#!/bin/bash
composer install
app/console doctrine:schema:update --force
Use -e to run it:
$ docker run -i -t -P
-v $PWD:/srv
-e DB_NAME=some_project_dev
-e INIT=bin/setup
Note that the -e option can be used multiple times in docer run, which looks pretty cool. Additionally, your startup script needs executable permissions (chmod +x).
Now we send a request to the container via curl to check if everything is working as expected. First, we need to get the public port mapped by Docker to port 80 of the container. Use the docker port command:
$ docker port $(docker ps -aql 1) 80
0.0.0.0:49153
docker ps -aql 1 is a good use The command can easily retrieve the ID of the last container. In our example, Docker maps the container's port 80 to port 49153. Let's curl it and take a look.
$ curl http://localhost:49153
You are not allowed to access this file. Check app_dev.php for more information.
When we don’t access the dev controller from localhost (Translator’s Note: Container’s localhost), we get Symfony's default error message. This is perfectly normal. Since we are not sending the curl request from inside the container, it is safe to remove these lines from the front controller web/app_dev.php.
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'] )
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1' )) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__ ).' for more information.');
}
These lines prevent any access to the dev controller from outside localhost.
Now it can work normally when you curl it, or use a browser to access http://localhost:49153/:
result.png
It’s easy! Now we can quickly start and update the environment, but there are still many areas that need improvement.
Original link: A PHP development environment with Docker (Translator: He Linchong Reviewer: Guo Lei)

The above introduces the PHP development environment based on Docker, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn