How to Add an External Package to n8n for PostgreSQL Connections in a Code Node workflow
By adding the external pg
package to a custom n8n
Docker image, you can easily use a Code node to interact with PostgreSQL. Here’s a step-by-step guide to achieve this.
Dockerfile
The Dockerfile
adds the PostgreSQL package (pg
) globally to the n8n
image.
# Use the latest official n8n image
FROM n8nio/n8n:latest
# Switch to root user to install additional packages
USER root
# Install the pg package globally
RUN npm install -g pg
# Revert back to the node user for security reasons
USER node
Build the Docker Image
To create a Docker image from the Dockerfile
, run the following commands in the same directory as the Dockerfile
:
# Build the Docker image
docker build -t n8n-with-pg .
# Verify the image creation
docker image ls
Docker Compose Configuration
Create a docker-compose.yml
file to manage your n8n
container. This example assumes you are using an external volume named n8n_data
for persistent storage.
volumes:
n8n_data:
external: true
services:
n8n:
container_name: n8n
image: n8n-with-pg
restart: always
ports:
- "port:port"
environment:
- ... your custom environments
- NODE_FUNCTION_ALLOW_EXTERNAL=pg
volumes:
- n8n_data:/home/node/.n8n
Run the Container
Start your container using Docker Compose:
sudo docker compose up -d
Now your n8n
container is set up with the pg
package pre-installed, ready to use for your workflows requiring PostgreSQL integration.
If you found this guide helpful, consider supporting us!
Extra:
Here's an example of how to use a Code node in n8n
to connect to a PostgreSQL database using the pg
package: