A PHP project containerization automatic deployment method and system based on a large language model agent
Patent Information
- Application Number
- CN202611103917.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-24
- Publication Date
- 2026-10-30
AI Technical Summary
本发明融合了项目源码的静态结构化解析与大语言模型的语义推理与闭环修正能力,实现了从PHP项目源码到可运行容器镜像的全自动化构建,为漏洞复现靶场的批量自动化搭建提供基础支撑,解决了现有大语言模型在生成PHP项目Dockerfile时存在的依赖版本偏差、扩展库缺失及错误修复泛化能力差等问题
[0075]1. 依赖信息精确提取:通过引入项目源码结构化解析机制,自动从composer.json中提取PHP版本约束、扩展依赖和框架类型,有效解决了大语言模型在缺乏项目上下文时容易产生的依赖版本偏差和扩展遗漏问题。
Smart Images

Figure CN123011255A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the fields of software automated deployment and network security technology. Specifically, it relates to a containerized automated deployment method and system for PHP projects based on a large language model intelligent agent, targeting web application vulnerability reproduction scenarios. Background Technology
[0002] In the field of cybersecurity, vulnerability reproduction is a crucial step in verifying the authenticity of vulnerabilities, assessing security threats, and confirming the effectiveness of patches. The first step in vulnerability reproduction typically involves containerizing a specific version of the software project based on the vulnerability report. This includes customizing Dockerfiles, mounting databases, and modifying configuration files, among other sub-steps, to build a runtime environment that can accurately trigger the vulnerability. With the increasingly rapid pace of vulnerability discovery and disclosure, manually building reproduction environments item by item can no longer meet the efficiency demands of large-scale vulnerability verification.
[0003] Among the many web technology stacks, containerized deployment of PHP web applications faces unique challenges. Unlike compiled languages with standardized build tools, PHP projects generally have weak constraints on build specifications and strong coupling with the runtime environment: for example, a specific version of the project may implicitly depend on a specific version of the PHP interpreter or database; the compilation and installation of some PHP extensions requires the pre-installation of corresponding Linux system-level development libraries; different frameworks (Laravel, Symfony, WordPress, etc.) have different web document root directory structures and file permission requirements. These factors make relying solely on generic Dockerfile templates or manually writing Dockerfiles time-consuming, laborious, and prone to errors.
[0004] In recent years, Large Language Models (LLMs) have demonstrated powerful capabilities in code generation, offering new possibilities for automated Dockerfile generation. However, existing Dockerfile generation methods based on LLMs have the following significant shortcomings:
[0005] 1. Lack of in-depth analysis capabilities of project source code. Large language models generate Dockerfiles based solely on project names or simple user descriptions, which can easily lead to dependency version discrepancies or omission of critical PHP extensions, causing the generated Dockerfile to fail to build.
[0006] 2. Lack of an effective closed-loop feedback and correction mechanism. Existing methods are mostly end-to-end single-build models, which cannot automatically analyze the cause of the error and perform targeted repairs when the generated Dockerfile fails to build;
[0007] 3. Noise issues in error logs. Docker build logs are typically extremely lengthy, containing a large amount of intermediate compilation output and irrelevant warnings. Directly submitting the full logs to a large language model is not conducive to accurately locating the root cause of errors.
[0008] 4. Lack of automatic detection and adaptation capabilities for project configuration files: It cannot automatically handle necessary deployment steps such as database connection configuration and SQL initialization script mounting in PHP projects.
[0009] In summary, there is currently a lack of a fully automated containerized deployment method for PHP projects that can coordinate source code analysis, semantic reasoning of large language models, and closed-loop feedback from Docker sandboxes. This is precisely the technical problem that this invention aims to solve. Summary of the Invention
[0010] This invention aims to overcome the aforementioned shortcomings of existing technologies and provide a method and system for the automated containerization and deployment of PHP projects based on a large language model intelligent agent. This invention integrates the static structured parsing of project source code with the semantic reasoning and closed-loop correction capabilities of a large language model, achieving fully automated construction from PHP project source code to a runnable container image. This provides fundamental support for the batch automated construction of vulnerability reproduction testbeds and solves problems such as dependency version discrepancies, missing extension libraries, and poor generalization ability in bug fixing that exist in existing large language models when generating PHP project Dockerfiles.
[0011] To achieve the above objectives, the technical solution of the present invention is as follows:
[0012] In a first aspect, the present invention provides a method for containerized automatic deployment of PHP projects based on large language model intelligent agents, comprising the following steps:
[0013] Step S1: Perform structured parsing of the target PHP project source code, extract structured environment information including framework type, target PHP version, required PHP extension modules and third-party dependency packages, and scan the project documentation to obtain deployment-related knowledge information to form a deployment knowledge context;
[0014] Step S2: Combine the structured environment information with the deployment knowledge context, and combine it with the preset PHPDockerfile framework template to construct structured prompt words, and generate the initial Dockerfile through a large language model;
[0015] Step S3: Execute image building on the current Dockerfile through Docker sandbox, capture build logs and perform intelligent cleaning and information compression, and use a large language model to determine the success / failure of the build result;
[0016] Step S4: When step S3 determines that the build has failed, the processed build error information and the current Dockerfile content are fed back to the large language model. The large language model analyzes the root cause of the error and generates a corrected Dockerfile, and then returns to step S3 to continue execution.
[0017] Step S5: When step S3 determines that the build was successful, output the final usable Dockerfile to complete the deployment.
[0018] Furthermore, step S1 specifically includes the following sub-steps:
[0019] S1.1 Framework and Version Identification
[0020] Parse the composer.json file in the project root directory, extract the PHP version constraint from the require field, and obtain the target major version number through regular expression matching;
[0021] Iterate through the dependencies with the ext- prefix in the require field, and remove the prefix to get a list of PHP extension modules;
[0022] The framework type of the project can be identified by the third-party package dependencies other than require-dev in the require field, including at least one of Laravel, Symfony, ThinkPHP, and WordPress;
[0023] Determine the root directory path of the web document based on the frame type;
[0024] S1.2 Document Knowledge Extraction
[0025] The system recursively scans the project directory according to a preset document matching pattern, matching deployment-related documents including README files, INSTALL installation instructions, .env environment variable template files, and docker-compose.yml files.
[0026] Exclude third-party dependencies and version control directories, including vendor, .git, and node_modules, during the scan;
[0027] The list of matched document paths is submitted to the large language model, which selects the documents most relevant to the deployment (up to 3 documents) and extracts a summary of key deployment information, including system dependencies, environment variables, web server configuration, and file permission requirements.
[0028] Furthermore, step S2 specifically includes the following sub-steps:
[0029] S2.1 Frame Template Provided
[0030] Provides a pre-defined layered PHP Dockerfile framework template, which uses a layered structure and includes the following components:
[0031] The operating system depends on the installation layer, which is used to install the system-level development libraries required for compiling PHP extensions;
[0032] The PHP extension installation layer installs the required PHP extension modules using the docker-php-ext-install command.
[0033] Composer Package Manager import layer;
[0034] The Web server document root directory configuration layer points the Web service root directory to the correct subdirectory based on the framework type.
[0035] Source code copying and dependency installation layer;
[0036] The runtime directory permission configuration layer ensures that web server users have write permissions to the cache and storage directories.
[0037] The structured prompts explicitly constrain the large language model: each installation command must be executed independently, and multiple commands should not be combined into a single RUN instruction.
[0038] S2.2 Structured Cue Keyword Construction
[0039] The framework type, PHP target version, required extension list, dependency package list, and deployment knowledge summary extracted by S1 are combined into a structured context and merged with the framework template to construct a system-level prompt word. The prompt word explicitly constrains the large language model: each installation command must be executed independently to reduce the difficulty of locating errors caused by merging commands; the corresponding Linux system-level development library must be installed for each PHP extension; and the web server document root directory and mod_rewrite module must be correctly configured according to the framework type.
[0040] S2.3 Post-processing verification
[0041] Perform format validation on the generated initial Dockerfile to ensure that each RUN command corresponds to an independent installation operation, there are no duplicate instructions, and comments and commands are written on separate lines.
[0042] Furthermore, step S3 specifically includes the following sub-steps:
[0043] S3.1 Log Cleaning and Compression
[0044] The full logs generated by Docker build are cleaned with ANSI escape sequences and terminal control characters. When the length of the cleaned logs exceeds a preset threshold (3000 characters), the basic environment information at the top of the logs and the error reporting area at the bottom of the logs are retained, the redundant compilation output content in the middle is discarded, and the truncated logs are used as the input for discrimination.
[0045] S3.2 LLM Construction Detection
[0046] The truncated logs are submitted to the large language model along with the current Dockerfile content, and judged according to the preset build success criteria. The criteria include: no fatal error "returned a non-zero code" at the end of the logs, completion markers such as "Generating autoload files" in the Composer dependency installation output, and no configuration failure markers such as "configure: error" in the PHP extension installation.
[0047] S3.3 Reflecting on Double Verification
[0048] If the initial assessment by S3.2 is successful, the assessment result, along with the Dockerfile and build logs, is resubmitted to the large language model. The large language model, acting as a quality auditer, re-examines the build logs to check for any overlooked hidden errors (such as Composer failing to run later due to ignoring platform requirements, PECL extension installation failing but the process continuing, or syntax errors in the web server configuration file). If hidden errors are found during the re-examination, the assessment result is corrected to failure, and the specific reason is output; non-fatal warnings are ignored.
[0049] Furthermore, step S4 specifically includes the following sub-steps:
[0050] S4.1 Error Diagnosis Prompts
[0051] This provides a predefined PHP build error diagnosis guide to the large language model, containing a mapping between typical error patterns and corresponding fixes. For example, the cause of `configure: error: ... not found` is a missing Linux system development library. A common fix is to add the missing library to `apt-get install`. This requires collecting a set of common extension-development library mappings [gd→libpng-dev, libjpeg-dev; zip→libzip-dev; intl→libicu-dev; xml→libxml2-dev, …]; as shown in Table 1.
[0052] Table 1
[0053]
[0054] S4.2 Context Constraint Correction
[0055] When prompting a large language model to modify the Dockerfile, several rules and constraints should be imposed: keep the beginning of the Dockerfile unchanged as much as possible, and make minimal changes to the end of the file first; if the error message indicates a temporary network failure, do not make any changes; disable non-essential modules that cause problems through build options; missing dependencies should be installed directly rather than just verified to exist.
[0056] S4.3 Iterative Control
[0057] A maximum iteration count threshold (10 times) is preset. Before returning to step S3 each time, the current iteration round is checked. If the threshold is not reached, the current version of the Dockerfile and the corresponding error message are recorded and the iteration continues. If the threshold is reached, the iteration is terminated and the failure result is output.
[0058] Furthermore, before executing the Docker image building in step S3, the method of the present invention also includes a preprocessing step of automatically locating and modifying configuration files independent of the Dockerfile:
[0059] First, the target PHP project's file directory tree, after removing irrelevant directories, is generated and submitted to the large language model. The large language model then locates the project's database connection configuration file based on preset configuration file recognition rules (firstly matching .env or .env.example, secondly config.php or config.php.dist, then wp-config.php, and finally database.php). At the same time, it determines whether the source file is a template file (such as .dist, .sample, or .example suffixes).
[0060] Then, the large language model determines the database name based on the project name and project document fragments: if the project is a known specific web application (such as Cacti, WordPress, etc.), it returns its agreed default database name; if it is a general framework application, it returns a general default name.
[0061] Next, the host, database name, username, and password fields in the database connection configuration are replaced with standard values corresponding to the Docker container orchestration environment. The large language model returns the modified complete file content and writes it to the target file.
[0062] Furthermore, the method also includes an automatic location step for the SQL initialization file:
[0063] The file directory tree is submitted to the large language model, which identifies the database initialization SQL file in the project by referring to the preset SQL file recognition rules (preferentially matching the patterns database.sql, structure.sql, schema.sql, etc.) and uses the identified SQL file path for mounting the database initialization volume in subsequent container orchestration.
[0064] Furthermore, after outputting the final usable Dockerfile in step S5, the service orchestration step is also included:
[0065] Automatically generate a docker-compose.yml orchestration file, which defines a multi-service orchestration that includes at least a web application service and a database service; inject database connection environment variables into the web application service to ensure consistency with the configuration modification results; in the database service, map the SQL initialization file to the docker-entrypoint-initdb.d directory of the database container via volume mount, and use the automatic initialization mechanism of the MySQL / MariaDB image to complete the initial creation and data population of the database.
[0066] Secondly, this invention provides an automated containerization deployment system for PHP projects based on a large language model intelligent agent, comprising:
[0067] Project parsing module: Performs structured parsing of the target PHP project source code, extracts framework type, PHP version, extension dependencies and third-party package dependencies, and scans project documentation to obtain deployment knowledge context.
[0068] Dockerfile generation module: Combines the extracted structured environment information with the preset PHP Dockerfile framework template, generates the initial Dockerfile through a large language model, and performs post-processing validation of the format.
[0069] Sandbox Execution and Judgment Module: Executes image building through Docker sandbox, intelligently cleans and compresses build logs, and uses a large language model to perform preliminary judgment and reflection verification on the build results.
[0070] The ReAct iterative correction module: When a build fails, it feeds back the error information and the current Dockerfile to the large language model, combines the predefined PHP build error diagnosis guide to analyze the root cause of the error and generate a corrected Dockerfile, driving the sandbox execution and discrimination module to re-execute.
[0071] Configuration orchestration module: Automatically locates and modifies the database configuration file in the project, identifies the SQL initialization file, determines the database name, and generates a docker-compose.yml orchestration file containing web services and database services after successful build, and completes the database initialization volume mounting.
[0072] Thirdly, the present invention provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the above-described method.
[0073] Fourthly, the present invention provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the above-described method.
[0074] Compared with the prior art, the present invention has the following beneficial effects:
[0075] 1. Precise extraction of dependency information: By introducing a structured parsing mechanism for project source code, PHP version constraints, extension dependencies, and framework types are automatically extracted from composer.json, effectively solving the problems of dependency version discrepancies and extension omissions that are prone to occur when large language models lack project context.
[0076] 2. Controllable Dockerfile structure: The generation of a large language model is guided by a pre-defined PHP Dockerfile layered framework template. Combined with the structured constraints that allow each command to be executed independently, the generated Dockerfile has a clear hierarchy and errors can be accurately located, which significantly reduces the difficulty of subsequent corrections.
[0077] 3. Effective Log Noise Compression: By constructing an intelligent cleaning and truncation strategy for logs (retaining the tail error area and discarding redundant intermediate compilation output), effective information compression of Docker's verbose build logs is achieved, ensuring that the large language model can focus on real error information rather than a large amount of noise data.
[0078] 4. Self-correcting closed loop: Through the designed ReAct closed-loop iteration mechanism, the large language model is transformed from a one-time generator into a self-correcting intelligent agent. It can autonomously analyze build errors, locate root causes, and generate targeted repair solutions within a limited number of rounds. Combined with the predefined PHP build error diagnosis guide, it significantly improves the final build success rate of Dockerfile.
[0079] 5. Improved reliability of judgment: By introducing a reflective dual verification mechanism, the large language model acts as an auditor to review the preliminary judgment results, which effectively reduces the risk of misjudgment caused by ignoring hidden errors and improves the accuracy of the judgment results.
[0080] 6. End-to-end environment integrity: Through the integration of automatic configuration file location and modification, SQL initialization file recognition, and automatic orchestration of docker-compose.yml, Dockerfile generation is extended from isolated image build script generation to complete runnable service environment orchestration, providing a complete infrastructure for the fully automated construction of vulnerability reproduction test ranges. Attached Figure Description
[0081] Figure 1 This is the overall architecture and workflow diagram of the PHP project containerization automatic deployment system based on a large language model intelligent agent provided in this embodiment of the invention.
[0082] Figure 2 This is a flowchart of the project analysis and knowledge extraction module provided in this embodiment of the invention.
[0083] Figure 3 This is a flowchart of the framework guidance Dockerfile generation and ReAct closed-loop iterative correction provided in the embodiments of the present invention.
[0084] Figure 4 This is the initial Dockerfile generation prompt framework used in the embodiments of the present invention.
[0085] Figure 5 This is the framework for construct error correction prompts used in embodiments of the present invention.
[0086] Figure 6 This is the configuration file location and modification prompt word framework used in the embodiments of the present invention. Detailed Implementation
[0087] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to the accompanying drawings and embodiments. The specific embodiments described herein are only for explaining the invention and are not intended to limit the invention.
[0088] I. System Overall Architecture
[0089] Combination Figure 1 As shown in the embodiment of the present invention, the PHP project containerization automatic deployment system based on a large language model intelligent agent mainly consists of the following core modules:
[0090] Configuration orchestration module (preprocessing stage). Before building the Docker image, the project file directory tree is generated using the source code path of the target PHP project as independent input. The large language model is called to determine the database name, locate and modify the configuration file content, and identify the SQL initialization file. The processing results (modified configuration information and SQL file path) are stored for later use.
[0091] Project parsing module. Executed in parallel or sequentially with the configuration orchestration module, it takes the PHP project source code path as input, performs structured parsing of composer.json, framework type detection, determination of the web document root directory, and extraction of project document deployment information, outputting structured environment information and deployment knowledge context.
[0092] Dockerfile generation module. Receives the output from the project parsing module, loads a pre-defined PHP Dockerfile layered framework template, constructs structured prompts, calls a large language model to generate the initial Dockerfile, and performs post-processing validation on the output.
[0093] Sandbox execution and discrimination module. It drives the Docker sandbox to execute `dockerbuild` via the Docker Engine API, performs ANSI cleaning and tail truncation compression on the build logs, and successively calls a large language model for initial success / failure discrimination and reflective double verification, outputting the build results and error analysis.
[0094] The ReAct iterative correction module receives build failure signals and error analysis information, combines them with a predefined PHP build error diagnosis guide, calls a large language model to analyze the root cause of the error and generates a corrected Dockerfile, writes it back to the build directory, and then drives the sandbox execution module to rebuild.
[0095] Configure the orchestration module (post-processing stage). After the Dockerfile is successfully built, read the configuration modification results and SQL file path stored in the preprocessing stage, automatically generate the docker-compose.yml orchestration file containing the web application service and database service, inject the database connection environment variables, and complete the volume mount configuration of the SQL initialization file.
[0096] II. Method and Flow
[0097] This invention provides a method for containerized automatic deployment of PHP projects based on large language model agents, comprising the following steps:
[0098] 1. Project Analysis and Knowledge Extraction
[0099] Combination Figure 2 As shown, after receiving the source code path of the target PHP project, the system performs the following operations:
[0100] (1) Framework and version identification.
[0101] The system first checks if a `composer.json` file exists in the project's root directory. If it exists, it parses the JSON content, locates the `php` key in the `require` field, extracts its version constraint string (e.g., ^8.2 or >= 8.1.0), and uses a regular expression to extract the major version number as the target PHP version (e.g., 8.2). If `composer.json` does not exist, it defaults to using the recommended stable version (PHP 8.2 / 7.2).
[0102] Next, iterate through all the key names in the require field, identify dependencies with the ext- prefix as PHP extension requirements, remove the prefix to get a list of extensions (e.g., ext-gd→gd), and store them in the extension list.
[0103] Then, the frame type is identified by the feature package name in the require field (Table 2):
[0104] Table 2
[0105]
[0106] If none of the above matches, the system will further check the directory structure: if wp-config.php exists, it is determined to be a WordPress project; if public / index.php exists, it is determined to be a general modern PHP project.
[0107] (2) Document knowledge extraction:
[0108] The system recursively scans for matching files in the project directory according to preset filename regular expression patterns (README.*, INSTALL.*, .env.example, .env, docker-compose.*, Makefile, docs / deploy.*, docs / install.*). During the scan, directories such as vendor, .git, node_modules, and storage are excluded to avoid scanning a large number of irrelevant files.
[0109] If a document file is matched, the system submits its path list to the large language model, which then selects up to three documents most relevant to the deployment and installation, and extracts key information summaries such as system dependencies, environment variables, web server configurations, and permission requirements. The large language model's specific analysis prompts explicitly require it to focus on: system-level library dependencies, key environment variables, web server rewrite rules and document root directory descriptions, and runtime directories requiring write permissions.
[0110] 2. Initial generation of the framework
[0111] Combination Figure 3As shown in the left half, the system executes the initial generation of the Dockerfile based on the structured environment information output in step 1:
[0112] (1) The system provides a preset PHP Dockerfile layered framework template as a structural reference. This framework template does not require the large language model to be copied verbatim, but rather demonstrates the expected layered structure through examples, which includes:
[0113] (a) Base image declaration: FROM php:<version number>-apache;
[0114] (b) System dependency installation layer: RUN apt-get update && apt-get install -y <system library list> && apt-get clean && rm -rf / var / lib / apt / lists / *;
[0115] (c) PHP extension installation layer: RUN docker-php-ext-install <extension list>;
[0116] (d) Composer introduction layer: COPY --from=composer:latest / usr / bin / composer / usr / bin / composer;
[0117] (e) Web server configuration layer: Modify Apache's DocumentRoot according to the framework's web root directory (use the sed command to replace the default path) and enable the mod_rewrite module;
[0118] (f) Code copying and dependency installation layer: First copy composer.json and composer.lock using Docker layer caching, execute composer install, and then copy all source code;
[0119] (g) Permission configuration layer: Execute chown -R www-data:www-data on runtime directories such as storage and cache.
[0120] (2) The system combines all the structured environment information (PHP version, extension list, framework type, Web root directory, dependency package list, deployment knowledge summary) extracted in step 1 with the framework template to form system prompt words. Its key constraints include: each installation command is an independent RUN instruction; the corresponding Linux system development library must be installed for the PHP extension; and the Web server root directory is configured according to the framework.
[0121] The initial Dockerfile generates a prompt word framework, such as Figure 4 As shown, this prompt is used to guide the large language model to generate a well-structured and hierarchical initial Dockerfile based on the project context.
[0122] (3) After the large language model outputs the Dockerfile content, the system performs post-processing verification: checking whether there are multiple commands merged into one RUN, whether there are duplicate RUN instructions, and whether comments are separated from commands on separate lines. If there are any problems, they are corrected again through the large language model.
[0123] 3. Sandbox execution and judgment
[0124] Combination Figure 3 As shown in the right half, the system enters a closed-loop iterative phase of generation → execution → judgment → correction:
[0125] (1) Sandbox execution: The system calls the docker build command through the Docker Engine API, using the directory where the Dockerfile is located as the build context to start image building. During the build process, the system receives the build logs returned by the Docker daemon in a streaming manner, records them one by one, and outputs them in real time. After the build is completed, the system returns the exit code and the complete log.
[0126] (2) Intelligent Log Cleaning and Compression: If the build returns a non-zero exit code or the log ends with error details, the system first performs ANSI escape sequence cleaning on the log to remove terminal color control characters and other non-text control sequences. After cleaning, the system calculates the total length of the log: if it exceeds the preset threshold of 3000 characters, it retains the basic environment information at the beginning of the log (approximately 500 characters) and the error reporting area at the end of the log (approximately 2500 characters), and replaces redundant compilation output in the middle (such as apt-get download progress bars, Composer package installation logs, etc.) with ellipses. If the log does not exceed the threshold, all content is retained.
[0127] (3) Success / Failure Determination: The system combines the compressed logs with the current Dockerfile content to form a determination message, which is then submitted to the large language model. The large language model is configured as a senior PHP DevOps engineer and makes the determination based on the following criteria:
[0128] (a) Does the log end with a fatal error such as "returned a non-zero code" or "configure: error"?
[0129] (b) If Composer is used, does the log show signs indicating that the package installation is complete, such as Generating autoload files?
[0130] (c) If docker-php-ext-install is run, does a configure error occur due to missing system libraries?
[0131] The large language model returns the results in structured JSON format: (True, None) indicates successful construction, and (False, "specific reasons for failure and suggested fixes") indicates construction failure.
[0132] (4) Reflect on double verification: If step (3) initially determines that the result is True (build successful), the system will resubmit the determination result along with the Dockerfile and logs to the large language model. This time, the large language model is set up as a quality auditor, focusing on checking for the following hidden errors:
[0133] (a) Composer uses the --ignore-platform-reqs flag to ignore platform requirements, which may result in missing runtime extensions later;
[0134] (b) Non-standard extended installation commands such as pecl install fail, but the Docker build process does not terminate;
[0135] (c) The Apache or Nginx configuration file has a syntax error but does not cause an abnormal build exit code.
[0136] If a hidden error is found during the review and verification, the judgment result will be corrected to (False, "specific reason for rejection"); non-fatal warning messages (such as Composer 2.2 is available, apt-get is deprecated, etc.) will be ignored, and the judgment of successful build will be maintained.
[0137] 4. ReAct Iterative Correction
[0138] (1) Error Analysis-Driven Correction: When step 3 determines that the build has failed, the system combines the complete content of the current Dockerfile with the processed error information, along with a predefined PHP build error diagnosis guide, and submits it to the large language model for correction. The diagnosis guide includes the following typical error patterns and their corresponding repair mappings:
[0139] (a) configure: error: ... not found → The corresponding Linux system development library is missing → Add the missing libraries (such as libpng-dev, libzip-dev, libicu-dev, libxml2-dev) to the apt-get install command list;
[0140] (b) Composer: requirements could not be resolved → Package dependency version conflict → Try adding the --ignore-platform-reqs option to bypass or upgrade the PHP base image version;
[0141] (c) Permission denied → Insufficient directory permissions → Add the chown www-data command to the corresponding directory;
[0142] (d) 404 error for a specific version download → Incorrect URL or version number → Check and correct the download link, or replace it with an available version.
[0143] (2) Revision Constraints: When prompting for revisions to the Dockerfile for the large language model, the system imposes the following additional constraints:
[0144] (a) Try to keep the beginning of the Dockerfile unchanged, and make minimal changes to the end of the file first;
[0145] (b) If the error message indicates a temporary network failure, no changes should be made;
[0146] (c) Disable non-essential modules that are causing problems (such as test modules) instead of deleting them via build options;
[0147] (d) Missing dependencies should be installed directly rather than simply verifying their existence.
[0148] (3) Iteration Control: The system maintains an iteration version counter (initial value is 1). Each time step 4 is entered, the current Dockerfile and corresponding error information are archived and saved to the history directory by version number, and then the version count is incremented by 1. Before generating the corrected Dockerfile and returning to step 3, the system checks whether the version count exceeds the preset threshold (10 times). If it has exceeded the threshold, the system terminates the iteration, records the final failure status, and outputs the last corrected version of the Dockerfile for manual analysis.
[0149] like Figure 5As shown, it demonstrates the framework for constructing error correction prompts, which are used to guide a large language model to analyze the root cause and generate a corrected Dockerfile when a Docker build fails.
[0150] 5. Service orchestration output
[0151] Once the Dockerfile is successfully built, the system automatically generates a docker-compose.yml orchestration file, which contains two core services:
[0152] (a) App service: Based on the successfully built Dockerfile image, map container port 80 to host port 8000, inject database connection environment variables (DB_HOST=db, DB_USERNAME, DB_PASSWORD, DB_DATABASE), and configure depend_on to depend on the database service to ensure the startup order.
[0153] (b) DB service: Using the MariaDB 10.6 image, the environment variables MYSQL_ROOT_PASSWORD, MYSQL_DATABASE, MYSQL_USER, and MYSQL_PASSWORD are configured to be consistent with the changes in the configuration file. The database is persistently stored and the SQL initialization file is mounted via volumes.
[0154] like Figure 6 The image shows a framework for prompting commands to locate and modify configuration files. This set of prompts is used for automatic location of configuration files, content modification, and identification of SQL initialization files.
[0155] 6. Configure automatic location and modification (preprocessing stage)
[0156] Before building the Docker image, the system independently performs automatic preprocessing of the configuration files, and the results are stored for subsequent service orchestration. This preprocessing stage can be executed in parallel or sequentially with step 1 (project parsing).
[0157] (1) Database Name Determination: The system first reads the first 2000 characters of the project's README document as context and submits it to the large language model. The large language model determines the standard database name of the project based on the project name and the document fragment. If the project belongs to a known specific application (e.g., Cacti → database name cacti), its conventional default name is returned; if it is a general framework project (e.g., a Laravel application), the general default name app_database is returned. This step ensures that the subsequent SQL initialization script can be correctly imported.
[0158] (2) Configuration file location: The system generates a project file directory tree (depth limited to 3 levels, filtering directories such as vendor, .git, node_modules, etc., but not restricting file extensions), submits it to the large language model, and requires it to locate the database connection configuration file according to the following priority rules (Table 3):
[0159] Table 3
[0160]
[0161] The large language model returns results in JSON format, including: whether the configuration file was found (found), the relative path of the source file (source_path), the path of the target file (target_path, the actual effective file name after removing the .dist / .sample / .example suffix), and whether it is a template file (is_template).
[0162] (3) Configuration Content Modification: If a configuration file is found and it is a template file, the system first copies the template file to the target file name. The system reads the complete content of the configuration file, submits it to the large language model, and requests that it replace the database host (DB_HOST) with db (Docker service name), the database name (DB_NAME) with the name determined in step (1), and the database username and password with the environment standard values. At the same time, it intelligently maps and replaces the relevant fields of the base URL (Site URL / Base URL). The large language model returns the modified complete file content, and the system writes it back to the original path.
[0163] (4) SQL Initialization File Recognition: The system submits the project file directory tree to the large language model again, requiring it to identify the database initialization SQL file based on the pattern (database.sql, structure.sql, schema.sql, or a .sql file named after the project). If the SQL file is identified, it will be mounted to the / docker-entrypoint-initdb.d / directory of the database container in the subsequent docker-compose orchestration, and the table structure creation and initial data import will be completed when the database starts for the first time using the automatic execution mechanism of the official MySQL / MariaDB image.
[0164] III. Verification of Technical Effects
[0165] Through the implementation of the above technical solution, this invention achieved a 97% success rate in building on 31 known project datasets, and achieved the following technical effects:
[0166] In terms of automated Dockerfile generation, by combining structured parsing of the composer.json file in the project source code with semantic extraction of the deployment document, the large language model can obtain accurate PHP version, extension dependencies, and framework information as the basis for generation, effectively reducing the problems of dependency version deviation and extension omission caused by missing information.
[0167] In terms of build error repair, the intelligent log cleaning and truncation strategy compresses the originally lengthy build logs, which may exceed tens of thousands of characters, into a summary of information focusing on the error area. Combined with the ReAct iterative correction mechanism of the PHP build error diagnosis guide, the large language model can accurately target and repair typical errors in the PHP ecosystem (such as extension compilation failure, Composer dependency conflicts, and runtime permission errors).
[0168] In terms of closed-loop control, the introduction of a reflective dual-verification mechanism effectively reduces false alarms (misjudging failure as success) and missed alarms (ignoring hidden errors) that may occur in a single judgment, thereby improving the reliability of the automated process. Setting an upper limit on the number of iterations (e.g., 10 times) ensures sufficient opportunities for correction while preventing infinite invalid loops.
[0169] In terms of environment integrity, end-to-end automation from a usable image to a complete runnable environment is achieved through automatic location and modification of configuration files, automatic identification and mounting of SQL initialization scripts, and automatic generation of docker-compose.yml, providing a ready-to-use target range infrastructure for subsequent vulnerability reproduction and verification.
[0170] The above description is merely a preferred embodiment of the present invention and does not limit the patent scope of the present invention. Any equivalent structural or procedural modifications made based on the description and drawings of the present invention, or direct or indirect applications in other related technical fields, are similarly included within the patent protection scope of the present invention.
Claims
1. A method for containerized automatic deployment of PHP projects based on large language model intelligent agents, characterized in that, Includes the following steps: Step S1: Perform structured parsing of the target PHP project source code, extract structured environment information including framework type, target PHP version, required PHP extension modules and third-party dependency packages, and scan the project documentation to obtain deployment-related knowledge information to form a deployment knowledge context; Step S2: Combine the structured environment information with the deployment knowledge context, and combine it with the preset PHPDockerfile framework template to construct structured prompt words, and generate the initial Dockerfile through a large language model; Step S3: Execute image building on the current Dockerfile through Docker sandbox, capture build logs and perform intelligent cleaning and information compression, and use a large language model to determine the success / failure of the build result; Step S4: When step S3 determines that the build has failed, the processed build error information and the current Dockerfile content are fed back to the large language model. The large language model analyzes the root cause of the error and generates a corrected Dockerfile, and then returns to step S3 to continue execution. During the iteration process, it is determined whether the current iteration round has reached the preset maximum number of iterations threshold. If it has, the iteration is terminated and the build failure result and the last generated Dockerfile are output. If it has not reached, the Dockerfile version of the current round and the corresponding error information are recorded and the next iteration round continues. Step S5: When step S3 determines that the build was successful, output the final usable Dockerfile to complete the deployment.
2. The method as described in claim 1, characterized in that, In step S1, the specific steps for extracting structured environmental information include: Parse the composer.json file in the project root directory, extract the PHP version constraint from the require field, and parse the target major version number as the PHP target version; Iterate through the dependencies with the ext- prefix in the require field, and remove the prefix to obtain the list of required PHP extension modules; The framework type of the project can be identified by the third-party package dependencies other than require-dev in the require field, including at least one of Laravel, Symfony, ThinkPHP, and WordPress; Determine the root directory path of the web document based on the frame type.
3. The method as described in claim 1, characterized in that, In step S1, the specific steps for scanning project documents to obtain deployment-related knowledge information include: The system recursively scans the project directory according to a preset document matching pattern, matching deployment-related documents including README files, INSTALL installation instructions, .env environment variable template files, and docker-compose.yml files. Exclude third-party dependencies and version control directories, including vendor, .git, and node_modules, during the scan; The list of matched document paths is submitted to the large language model, which then selects the documents most relevant to the deployment and extracts a summary of key deployment information, including system dependencies, environment variables, web server configurations, and file permission requirements.
4. The method as described in claim 1, characterized in that, In step S2, the preset PHP Dockerfile framework template adopts a layered structure, which includes the following in sequence: The operating system depends on the installation layer, which is used to install the system-level development libraries required for compiling PHP extensions; The PHP extension installation layer installs the required PHP extension modules using the docker-php-ext-install command. Composer package manager import layer; The Web server document root directory configuration layer points the Web service root directory to the correct subdirectory based on the framework type. Source code copying and dependency installation layer; The runtime directory permission configuration layer ensures that web server users have write permissions to the cache and storage directories. The structured prompts explicitly constrain the large language model: each installation command must be executed independently, and multiple commands should not be combined into a single RUN instruction.
5. The method as described in claim 1, characterized in that, Step S3, the specific steps for intelligent cleaning and information compression include: Clean the build logs using ANSI escape sequences and terminal control characters; When the length of the cleaned log exceeds the preset threshold, retain the basic environment information in the log header and the error reporting area of the last few thousand characters in the log tail, and discard the redundant intermediate compilation output. The truncated logs are submitted to the large language model along with the current Dockerfile content. The large language model then judges the success of the build based on preset build success criteria, which include: fatal errors with no non-zero exit codes at the end of the logs, Composer dependencies being installed and generating autoload files, and configuration errors caused by missing system libraries in the PHP extension installation.
6. The method as described in claim 1, characterized in that, In step S3, after using the large language model to judge the construction results, a reflection and verification step is also included: When the build is initially determined to be successful, the determination result, Dockerfile content, and build logs are resubmitted to the large language model. The large language model then reviews the build logs again as a quality auditing role to check for any hidden errors that have been overlooked. These hidden errors include: Composer failing to run in subsequent cycles due to ignoring platform requirements, PECL extension installation failing but the build process continuing, and syntax errors in the web server configuration file. If a hidden error is discovered during the review and verification process, the result will be corrected to "build failed" and the specific reason for the failure will be output.
7. The method as described in claim 1, characterized in that, In step S4, during the step of analyzing the root cause of errors by the large language model and generating a corrected Dockerfile, a predefined PHP build error diagnosis guide is provided to the large language model. This guide includes a mapping relationship between typical error patterns and corresponding repair actions, including: 。 8. The method as described in claim 1, characterized in that, Before or after step S3, which involves building the Docker image, there is also a step for automatically locating and modifying configuration files. Generate the file directory tree of the target PHP project and submit it to the large language model. The large language model will locate the database connection configuration file of the project according to the preset configuration file recognition rules and determine whether it is a template file. If it is a template file, first copy the template file as the target file; Read the contents of the configuration file and submit them to the large language model. The large language model replaces the database host, database name, database username and password fields with the standard values corresponding to the Docker container environment, returns the modified complete file contents and writes them to the target file. The database name is determined as follows: if the project is a known specific web application, the default database name is queried or the database name is inferred from the project name and project documentation through a large language model; if the project is a general framework application, the general default database name is used.
9. The method as described in claim 1, characterized in that, After step S5 outputs the final usable Dockerfile, the following is also included: The file directory tree is submitted to the large language model, which identifies the database initialization SQL file in the project and records the path of the identified SQL file. Automatically generate a docker-compose.yml orchestration file, which defines a multi-service orchestration that includes at least web application services and database services; Inject a database connection environment variable into the Web application service, ensuring that its value is consistent with the database connection information modified in the configuration file in the previous step. In the database service, the SQL initialization file is mapped to the initialization entry directory of the database container via volume mounting, so as to achieve automatic database initialization when the container starts for the first time.
10. A containerized automatic deployment system for PHP projects based on a large language model intelligent agent, characterized in that, include: The project parsing module is used to perform structured parsing of the source code of the target PHP project, extracting structured environment information including framework type, target PHP version, required PHP extension modules and third-party dependency packages, and scanning project documentation to obtain deployment knowledge context; The Dockerfile generation module is used to combine the structured environment information with the deployment knowledge context, and combine it with a preset PHP Dockerfile framework template to generate an initial Dockerfile through a large language model; The Sandbox Execution and Discrimination module is used to execute image building on the current Dockerfile through the Docker sandbox, capture and intelligently clean the build logs, and use a large language model to perform success / failure discrimination and reflection verification on the build results. The ReAct iterative correction module is used to feed back the build error information and the current Dockerfile to the large language model when the build fails. The large language model analyzes the root cause of the error according to the predefined PHP build error diagnosis guidelines and generates a corrected Dockerfile, which drives the sandbox execution and discrimination module to re-execute. The configuration orchestration module is used to automatically locate and modify the database configuration file in the project, identify the SQL initialization file, and generate a docker-compose.yml orchestration file containing web services and database services after a successful build.
