N8n running python script

Hey Jan, how are you? hope you are doing well

I saw your contribution in some posts here in the n8n community and I will be really appreciated if you can help me with an n8n python scripts running case.

I have a n8n hosted on VPS with Coolify panel and I want it to run at some point in the workflow to run a Python script hosted also on the same VPS. I have created a Python worker container on Coolify so I can make it control all Python work (picture 1)

This python-worker container was created on Coolify using a Github repository has a dockerfile (picture 2)

when I tried to run the container from inside n8n workflow with the execute command node (picture 3)

I got the error you see “/bin/sh: docker not found”

Am I trying to run the scripts in a right way? and where is the issue here

@jan Have a look please @A_A4

Hi @nader95

Most likely: You are trying to run the docker command from inside the n8n container, but the n8n image does not have the Docker CLI installed or access to the host’s Docker socket.

Try:
• Add an SSH node to your workflow instead of the “Execute Command” node.
• Connect the SSH node to your VPS host IP using your server credentials.
• Execute the command docker exec python-worker python /data/scripts/test.py via the SSH node.
• Ensure the SSH user has permission to run Docker (add the user to the docker group).

hope this help!

2 Likes

First of all thanks for your time and help I really appreciate it. Let me try that method.

Is it the best solution to run a Python script as compatibility and for future updates? as I saw many recommendation for using FastAPI and n8n task runners, but I don’t have any experience with these two.

What i know is wrapping your script in a simple API (using FastAPI) is the superior, future-proof solution compared to SSH.because when using SSH, if you change your server password or keys, the automation breaks. It also grants n8n “root” access, which is a security risk.

1 Like

Aha Great got it, final request, if you have any guides for this FastAPI part to and how to develop it, I will be very grateful.

1 Like
from fastapi import FastAPI
import subprocess

app = FastAPI()

@app.post("/run-script")
async def run_script():
    # Runs your existing script
    result = subprocess.run(["python", "/data/scripts/test.py"], capture_output=True, text=True)
    return {"output": result.stdout, "error": result.stderr}

try theses steps:
• Update your requirements.txt to include fastapi and uvicorn.
• Add a simple main.py to your repository (see guide below) to accept a POST request and run your logic.
• Change the CMD in your Dockerfile to: CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "3000"].
• Replace the SSH node in n8n with an HTTP Request node pointing to http://<container-name>:3000/run-script.

hope this helps!

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.