How to run Node.js script from PHP while it runs in a Docket container

Posted on December 29, 2024

To call app.js (your Node.js script) from PHP when it is executed in a Docker container, you can use the following approach:


1. Command to Run app.js Inside the Docker Container

Ensure your Dockerfile is set up to execute app.js as its main script.

Example Dockerfile:

FROM node:18-alpine WORKDIR /usr/src/app COPY app.js . CMD ["node", "app.js"]

Build the Docker image:

docker build -t my-node-app .

This sets up the my-node-app image to run app.js by default.


2. PHP Script to Call app.js

Use PHP's shell_exec() or exec() function to invoke the Node.js script through Docker.

Example call-node.php:

<?php
// Command to run the app.js script in the Docker container
$command = 'docker run --rm my-node-app';
// Execute the command $output = shell_exec($command);
// Display the output of the Node.js script
echo "Output from Node.js: " . $output;
?>

3. Run the PHP Script

You can run this PHP script:

  • From the Command Line:

    php call-node.php
  • From a Web Server: Save call-node.php in your web server's root directory (e.g., /var/www/html) and access it via your browser, e.g., http://localhost/call-node.php.


4. Explanation

  • docker run --rm my-node-app: This runs the app.js script inside the Docker container created from the my-node-app image. The --rm flag removes the container after execution.
  • shell_exec($command): Executes the Docker command and captures the output.

Optional: Directly Run app.js Without Docker

If you don't want to involve Docker, you can run the script directly using Node.js installed on the server:

PHP Example:

<?php
// Command to run app.js using Node.js
$command = 'node /path/to/app.js';
// Execute the command
$output = shell_exec($command);
// Display the output
echo "Output from Node.js: " . $output;
?>

This requires Node.js to be installed on the server and the correct path to app.js.