search
HomeBackend DevelopmentPHP TutorialBest Practices for Docker Compose, Nginx, and MariaDB: Highly Available PHP Application Architectural Design

Docker Compose、Nginx和MariaDB的最佳实践:高可用PHP应用程序架构设计

Best Practices for Docker Compose, Nginx and MariaDB: Highly Available PHP Application Architecture Design

Introduction:
In today’s Internet era, building high availability applications are becoming increasingly important. As the number of Internet users increases, application performance, reliability, and scalability become key considerations. This article will introduce how to use Docker Compose, Nginx and MariaDB to design a highly available PHP application architecture, and provide specific code examples.

Part One: Architecture Overview
We want to build a highly available PHP application that needs to meet the following requirements:

  1. High reliability: able to provide high availability The application can automatically switch to the backup server when the server fails or the network is abnormal.
  2. Scalability: Able to dynamically scale the capacity of the application according to demand to cope with sudden high concurrent access.
  3. Performance Optimization: Improve application performance and response speed by using Nginx as a reverse proxy server and load balancer.
  4. Database Reliability: Use MariaDB as the application's database and ensure data reliability and consistency.

Part 2: Building a Docker Image
Before building a highly available PHP application, we first need to package the application and all dependencies into a Docker image. You can use a Dockerfile to define the build process of a Docker image.

The following is a sample Dockerfile:

# 使用基础PHP镜像
FROM php:7.4-fpm

# 安装PHP依赖项
RUN apt-get update && apt-get install -y 
    git 
    zip 
    curl 
    libpng-dev 
    libonig-dev 
    libxml2-dev 
    && docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

# 设置工作目录
WORKDIR /var/www/html

# 将应用程序复制到工作目录
COPY . .

# 安装依赖项
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN composer install --no-scripts --no-autoloader

# 自动生成Autoload文件
RUN composer dump-autoload --optimize

# 修改文件权限
RUN chown -R www-data:www-data /var/www/html/storage

# 启动PHP-FPM服务器
CMD ["php-fpm"]

# 暴露端口
EXPOSE 9000

Using the above Dockerfile, we can build a Docker image that contains the application and all dependencies. The image can be built using the following command:

docker build -t myapp .

Part 3: Building the architecture using Docker Compose
Next, we will use Docker Compose to define and manage the entire high-availability PHP application architecture. Docker Compose is a tool for defining and running multi-container Docker applications.

The following is an example docker-compose.yaml file:

version: '3'
services:
  app:
    build: 
      context: .
      dockerfile: Dockerfile
    volumes:
      - .:/var/www/html
    ports:
      - 9000
    networks:
      - my-network
  nginx:
    image: nginx
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
      - ./site.conf:/etc/nginx/conf.d/default.conf
    ports:
      - 80:80
    depends_on:
      - app
    networks:
      - my-network
  db:
    image: mariadb
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: 'password'
    networks:
      - my-network

networks:
  my-network:

In the docker-compose.yaml file of the above example, we define three services: app, nginx and db. Among them, the app service is the PHP application image we built before. The nginx service uses the official image of Nginx. The db service is the official image of MariaDB.

We also defined a network named my-network to connect these three services.

Part 4: Configure Nginx as a reverse proxy server and load balancer
In order to improve the performance and response speed of the application, we will use Nginx as a reverse proxy server and load balancer.

The following is an example nginx.conf file:

user www-data;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
    multi_accept on;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    access_log /var/log/nginx/access.log combined;

    gzip on;
    gzip_disable "msie6";

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    include /etc/nginx/conf.d/*.conf;
}

In the above example, we specified the configuration of Nginx. Next, we need to define a site configuration for Nginx.

The following is an example site.conf file:

server {
    listen 80;
    server_name myapp.example.com;

    location / {
        proxy_pass http://app:9000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        client_max_body_size 100M;

        proxy_buffering off;
        proxy_request_buffering off;
    }
}

In the above example, we defined an Nginx virtual host to proxy all HTTP requests to the 9000 port of the app service.

Part 5: Running Architecture
Use the following command to start the highly available PHP application architecture we defined:

docker-compose up -d

Now, our highly available PHP application has successfully run . The usability and performance of the application can be tested by visiting http://myapp.example.com.

Conclusion:
By using Docker Compose, Nginx and MariaDB, we can design and build a highly available PHP application architecture. Docker Compose can help us define and manage multi-container applications, Nginx can provide high-performance reverse proxy and load balancing functions, and MariaDB can provide reliable and stable database services. Through this architecture, we can improve the availability, reliability and performance of applications and meet user needs for high-quality applications.

The above is the detailed content of Best Practices for Docker Compose, Nginx, and MariaDB: Highly Available PHP Application Architectural Design. For more information, please follow other related articles on the PHP Chinese website!

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

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 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.

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools