search
HomeBackend DevelopmentPHP TutorialDetailed tutorial on setting up a Docker-based PHP development environment_PHP tutorial

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 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.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.