


Detailed 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.
?
|
$ alias composer="docker run -i -t -v $PWD:/srv ubermuda/composer"
|
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:
?
2 3 4 5 6 7 8 9 10 11
|
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 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:
?
2 3 4 5
6 7 8
10 11 12 13
|
[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 | /etc/init.d/mysql start app/console doctrine:schema:update --force /etc/init.d/mysql stop exec /usr/bin/supervisord |
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 |
1 2 | $ cd docker-symfony $ docker build -t symfony . |
Now, you can use it to run your Symfony project:
?
2
|
$ cd SomeProject $ docker run -i -t -P -v $PWD:/srv symfony
|
-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 |
?
1
|
$ 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
3 |
|
1 2 3 4 | $ docker run -i -t -P -v $PWD:/srv -e DB_NAME=some_project_dev -e INIT=bin/setup |
1 2 | $ docker port $(docker ps -aql 1) 80 0.0.0.0:49153 |
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.
?
2 3 ![]() 6 |
// 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.');
}
|

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

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

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

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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