Table of Contents
Detailed tutorial on building a PHP development environment based on Docker
Home Backend Development PHP Tutorial Detailed tutorial on setting up a Docker-based PHP development environment_PHP tutorial

Detailed tutorial on setting up a Docker-based PHP development environment_PHP tutorial

Jul 13, 2016 am 09:47 AM
docker php based on develop build Tutorial environment of detailed

Detailed tutorial on building a PHP development environment based on Docker

This article mainly introduces a detailed tutorial on building a PHP development environment based on Docker. Docker is the latest virtual machine technology at the moment. Best choice, friends in need can refer to it

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 method 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:

You can use it as you like. 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 PHP development environment

At present, web applications are complex and the PHP development environment requires a lot of things. In order to ensure the simplicity of the environment, various restrictions need to be made.

This time we use Nginx, PHP5-FPM, and MySQL to run the Synmfony project.

 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.

Multi-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.

Initialization 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.

 ?

1

$ alias composer="docker run -i -t -v $PWD:/srv ubermuda/composer"

1

$ alias composer="docker run -i -t -v $PWD:/srv ubermuda/composer"

1

$ composer create-project symfony/framwork-standard-edition SomeProject

Now you can initialize the Symfony project:  ?
1 $ composer create-project symfony/framwork-standard-edition SomeProject

So cool! Let’s do some 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. Just 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:

 ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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"]

1

2

3

4

5

6

7

8

9

10

11

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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 ~ [^/].php(/|$) {

fastcgi_pass unix:/var/run/php5-fpm.sock;

include fastcgi_params;

}

}

12 13 14 15 16 17 18 19 20 21 22
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 start by extending the debian:wheezy base image, and then configure Nginx and PHP5-FPM through a series of sed commands. Copy the code. The code is as follows:  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:  ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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 ~ [^/].php(/|$) { fastcgi_pass unix:/var/run/php5-fpm.sock; include fastcgi_params; } }

Since we don’t need a domain name, we set server_name to _ (a bit like perl’s $_ placeholder variable), and configure the document root to /svr/web. We will deploy the application in /srv, the rest is the standard Mginx PHP5-FPM configuration.

Since a container can only run 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! Here is a small snippet of supervisord's configuration:

 ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

[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

1

2

3

4

5

1

2

3

4

5

/etc/init.d/mysql start

app/console doctrine:schema:update --force

/etc/init.d/mysql stop

 

exec /usr/bin/supervisord

6

7

8

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#!/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

9

10

11

12

13

1

2

$ cd docker-symfony

$ docker build -t symfony .

14 15 16 17
[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 services and add a special program:init process. It is not an actual service, but an original way of running startup scripts. 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 would look like this:  ?
1 2 3 4 5 /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 change the method and let the supervisor run it and never restart it. The actual init.sh script is as follows:  ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #!/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
The script first waits for MySQL to start, then creates a DB according to the environment variable DB_NAME, which defaults to symfony, and then finds the script to run in the INIT environment variable and tries to run it. The end of this article explains how to use these environment variables. Build and run the image Everything is ready, all we need is the east wind. We also need to build the Symfony Docker image, using the docker build command:  ?
1 2 $ cd docker-symfony $ docker build -t symfony .

Now, you can use it to run your Symfony project:

 ?

1

2

$ cd SomeProject

$ docker run -i -t -P -v $PWD:/srv symfony

1

2

$ 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 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.

1

$ docker run -i -t -P -v $PWD:/srv -e DB_NAME=some_project_dev symfony

-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.

1

2

3

#!/bin/bash

composer install

app/console doctrine:schema:update --force

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:

 ?

1

1

2

3

4

$ docker run -i -t -P

-v $PWD:/srv

-e DB_NAME=some_project_dev

-e INIT=bin/setup

$ docker run -i -t -P -v $PWD:/srv -e DB_NAME=some_project_dev symfony

The INIT environment variable is even more powerful, allowing 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:

1

2

$ docker port $(docker ps -aql 1) 80

0.0.0.0:49153

 ?

1

2

1

$ curl http://localhost:49153

3

1

You are not allowed to access this file. Check app_dev.php for more information.

#!/bin/bash composer install app/console doctrine:schema:update --force
Run it with -e:  ?
1 2 3 4 $ 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 80 mapped by Docker to the container and use the docker port command:  ?
1 2 $ docker port $(docker ps -aql 1) 80 0.0.0.0:49153
Docker ps -aql 1 is a useful command that 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.  ?
1 $ curl http://localhost:49153
 ?
1 You are not allowed to access this file. Check app_dev.php for more information.

When we access the dev controller not from localhost (Translator's Note: localhost of the container), we get Symfony's default error message, which is normal, because we are not sending curl requests from inside the container, so, yes Safely remove these lines from web/app_dev.php in the front controller.

 ?

1

2

3

4

5

6

7

8

9

// 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.');

}

1

2

3
201571105429165.png (1554×988)4
5

6

8 9
// 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 curling, or use a browser to access http://localhost:49153/: http://www.bkjia.com/PHPjc/1025314.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1025314.htmlTechArticleDetailed tutorial on building a Docker-based PHP development environment. This article mainly introduces how to build a Docker-based PHP development environment. Detailed tutorial, Docker is the best choice for current virtual machine technology, you need...
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

How to exit the container by docker How to exit the container by docker Apr 15, 2025 pm 12:15 PM

Four ways to exit Docker container: Use Ctrl D in the container terminal Enter exit command in the container terminal Use docker stop <container_name> Command Use docker kill <container_name> command in the host terminal (force exit)

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to copy files in docker to outside How to copy files in docker to outside Apr 15, 2025 pm 12:12 PM

Methods for copying files to external hosts in Docker: Use the docker cp command: Execute docker cp [Options] <Container Path> <Host Path>. Using data volumes: Create a directory on the host, and use the -v parameter to mount the directory into the container when creating the container to achieve bidirectional file synchronization.

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

How to restart docker How to restart docker Apr 15, 2025 pm 12:06 PM

How to restart the Docker container: get the container ID (docker ps); stop the container (docker stop <container_id>); start the container (docker start <container_id>); verify that the restart is successful (docker ps). Other methods: Docker Compose (docker-compose restart) or Docker API (see Docker documentation).

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

See all articles