在現代軟體開發領域,容器化已成為高效部署和可擴展性的基石。 Docker 可以輕鬆地將應用程式及其相依性打包到可移植容器中。在本部落格中,我們將引導您使用 Docker Compose 建立多容器 PHP 和 MySQL 應用程式。
為什麼對 PHP 和 MySQL 使用 Docker?
一致性:在開發和生產的所有階段都在同一環境中運行您的應用程式。
隔離:將 PHP 和 MySQL 等服務保存在單獨的容器中,以實現模組化和可維護的設定。
易於擴展:隨著應用程式的成長,輕鬆新增或刪除容器。
專案結構
您的專案目錄應如下所示:
project/ │ ├── php-app/ │ ├── Dockerfile │ └── index.php │ └── docker-compose.yml
Docker 撰寫文件
這是 docker-compose.yml 檔案:
version: '3.8' services: php-app: build: ./php-app # Builds the PHP app Docker image from the ./php-app directory ports: - "8080:80" # Maps port 8080 on the host to port 80 in the container depends_on: - mysql # Ensures MySQL starts before the PHP app mysql: image: mysql:8.0 # Uses the official MySQL image ports: - "3306:3306" # Maps port 3306 on the host to port 3306 in the container environment: MYSQL_ROOT_PASSWORD: root # Root password for MySQL MYSQL_DATABASE: mydb # Initial database to create volumes: - mysql-data:/var/lib/mysql # Persists MySQL data in a named volume volumes: mysql-data: # Declares a named volume for MySQL data persistence
PHP應用程式程式碼
index.php 檔案連接到 MySQL 容器:
<?php $servername = "mysql"; // Service name defined in docker-compose.yml $username = "root"; $password = "root"; $database = "mydb"; try { // Create connection $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password); // Set PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected to MySQL successfully!"; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
PHP 應用程式的 Dockerfile
Dockerfile 建置具有所需相依性的 PHP 容器:
# Use the official PHP image FROM php:8.2-apache # Install PDO MySQL extension RUN docker-php-ext-install pdo pdo_mysql # Set the working directory WORKDIR /var/www/html # Copy the application code COPY index.php . # Expose port 80 EXPOSE 80
建置和運行的步驟
建立目錄結構
- 將 Dockerfile 和 index.php 放在 php-app 資料夾中。
- 將 docker-compose.yml 放在專案根資料夾中。
建置並啟動容器在專案目錄中開啟終端並運行:
docker-compose up --build
造訪 PHP 應用程式 在瀏覽器中造訪 http://localhost:8080。如果一切設定正確,您應該看到:
Connected to MySQL successfully!
驗證 MySQL 資料庫
使用 MySQL 用戶端或 MySQL Workbench。
使用以下命令連接到 localhost:3306:
使用者名稱:root
密碼:root
驗證資料庫 mydb 是否已建立。
此設定的主要特點
服務依賴管理:depends_on 確保 MySQL 在 PHP 應用程式之前啟動。
資料持久化:mysql-data卷儲存MySQL數據,防止容器重新啟動後遺失。
連接埠映射:透過映射到主機的連接埠輕鬆存取服務。
擴充設定
將更多服務(如 Nginx 或 Redis)加入 Compose 檔案。
使用 .env 檔案來管理敏感配置。
使用 Docker Compose 的縮放選項來水平縮放服務。
結論
透過此設置,您已經使用 Docker Compose 建立了一個可擴展的模組化 PHP 和 MySQL 應用程式。容器化可簡化環境管理並為您的應用程式雲端部署做好準備。無論您是初學者還是經驗豐富的開發人員,Docker 都是現代應用程式開發不可或缺的工具。
準備好將您的設定提升到新的水平了嗎?嘗試將其與 CI/CD 管道或 Kubernetes 整合以實現生產級環境。
以上是Dockerize 您的 PHP 和 MySQL 應用程式:多容器應用程式逐步指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

使用依賴注入(DI)的原因是它促進了代碼的松耦合、可測試性和可維護性。 1)使用構造函數注入依賴,2)避免使用服務定位器,3)利用依賴注入容器管理依賴,4)通過注入依賴提高測試性,5)避免過度注入依賴,6)考慮DI對性能的影響。

phpperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovessetimes.2)優化

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

TOOPTIMIZEPHPAPPLICITIONSFORPERSTORANCE,USECACHING,數據庫imization,opcodecaching和SererverConfiguration.1)InlumentCachingWithApcutCutoredSatfetchTimes.2)優化的atabasesbasesebasesebasesbasesbasesbaysbysbyIndexing,BeallancingAndWriteExing

依賴性注射inphpisadesignpatternthatenhancesFlexibility,可檢驗性和ManiaginabilybyByByByByByExternalDependencEctenceScoupling.itallowsforloosecoupling,EasiererTestingThroughMocking,andModularDesign,andModularDesign,butquirscarecarefulscarefullsstructoringDovairing voavoidOverOver-Inje

PHP性能優化可以通過以下步驟實現:1)在腳本頂部使用require_once或include_once減少文件加載次數;2)使用預處理語句和批處理減少數據庫查詢次數;3)配置OPcache進行opcode緩存;4)啟用並配置PHP-FPM優化進程管理;5)使用CDN分發靜態資源;6)使用Xdebug或Blackfire進行代碼性能分析;7)選擇高效的數據結構如數組;8)編寫模塊化代碼以優化執行。

opcodecachingsimplovesphperforvesphpermance bycachingCompiledCode,reducingServerLoadAndResponSetimes.1)itstorescompiledphpcodeinmemory,bypassingparsingparsingparsingandcompiling.2)useopcachebachebachebachebachebachebachebysettingparametersinphametersinphp.ini,likeememeryconmorysmorysmeryplement.33)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SublimeText3漢化版
中文版,非常好用

SublimeText3 Linux新版
SublimeText3 Linux最新版

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器