Skip to content

mediafill/Coolify-Node-Postgres-Deploy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 

Repository files navigation

1.0 Coolify API Reference for Deployment

The core of this automated workflow is the agent's ability to interact with the Coolify API. This section provides an annotated reference for the critical API endpoints and their corresponding curl commands required to deploy a Node.js and PostgreSQL application. The API is accessed with a bearer token for authorization.10 The commands are designed to be executed by the Claude Code agent, which will dynamically generate the required parameters. The use of a JSON parsing tool like jq is indispensable for extracting dynamic data from API responses, which is necessary for chaining commands together.21

1.0.1 Coolify API Call Sequence

Below are the primary actions in a typical deployment pipeline. Each endpoint returns data that can be chained into subsequent calls (e.g., project UUID, service UUID, database internal URL).

Create Project (POST /api/v1/projects)

Headers: Authorization (Bearer), Content-Type 23
Data extraction: ..uuid or ..id 22

curl -s -X POST "$COOLIFY_URL/api/v1/projects" \
  --header "Authorization: Bearer $COOLIFY_API_TOKEN" \
  --header 'Content-Type: application/json' \
  --data '{"name":"string","description":"string"}'

List Projects (GET /api/v1/projects)

Headers: Authorization 11
Data extraction: . | select(.name=="<project_name>") | .id 21

curl -s "$COOLIFY_URL/api/v1/projects" \
  --header "Authorization: Bearer $COOLIFY_API_TOKEN"

Create PostgreSQL Database (POST /api/v1/databases/postgresql)

Headers: Authorization, Content-Type
Data extraction: .uuid, .internal_db_url

curl -s -X POST "$COOLIFY_URL/api/v1/databases/postgresql" \
  --header "Authorization: Bearer $COOLIFY_API_TOKEN" \
  --header 'Content-Type: application/json' \
  --data '{"server_uuid":"string","project_uuid":"string","environment_name":"production","name":"string","postgres_user":"string","postgres_password":"string","postgres_db":"string","image":"postgres:15-alpine","instant_deploy":true,"destination_uuid":"string"}'

Create Docker Compose Service (POST /api/v1/services)

Headers: Authorization, Content-Type
Data extraction: .uuid, .domains

curl -s -X POST "$COOLIFY_URL/api/v1/services" \
  --header "Authorization: Bearer $COOLIFY_API_TOKEN" \
  --header 'Content-Type: application/json' \
  --data '{"server_uuid":"string","project_uuid":"string","environment_name":"production","name":"string","description":"string","docker_compose_raw":"<base64_encoded_compose>","instant_deploy":false,"destination_uuid":"string"}'

Start Service (POST /api/v1/services/{uuid}/start)

Headers: Authorization, Accept
Data extraction: .message

curl -s -X POST "$COOLIFY_URL/api/v1/services/${SERVICE_UUID}/start" \
  --header "Authorization: Bearer $COOLIFY_API_TOKEN" \
  --header 'Accept: application/json'

Restart Service (POST /api/v1/services/{uuid}/restart)

Headers: Authorization, Accept
Data extraction: .message

curl -s -X POST "$COOLIFY_URL/api/v1/services/${SERVICE_UUID}/restart" \
  --header "Authorization: Bearer $COOLIFY_API_TOKEN" \
  --header 'Accept: application/json'

Get Service Status (GET /api/v1/services/{uuid})

Headers: Authorization, Accept
Data extraction: .status, .applications[].status, .databases[].status

curl -s -X GET "$COOLIFY_URL/api/v1/services/${SERVICE_UUID}" \
  --header "Authorization: Bearer $COOLIFY_API_TOKEN" \
  --header 'Accept: application/json'

List All Services (GET /api/v1/services)

Headers: Authorization, Accept
Data extraction: .[].uuid, .[].name, .[].status

curl -s -X GET "$COOLIFY_URL/api/v1/services" \
  --header "Authorization: Bearer $COOLIFY_API_TOKEN" \
  --header 'Accept: application/json'

Note: The Coolify API has evolved to include database creation and Docker Compose service management endpoints. The docker_compose_raw field must be base64 encoded, and environment_name should be used instead of environment_id for most operations.

1.1 The Full Deployment Playbook (Step-by-Step)

The following sequence of instructions is the core of the agentic playbook. It demonstrates how to guide Claude Code to execute the entire deployment pipeline.

Step 1: Provisioning the Database

The first step is to provision the PostgreSQL database instance. The Coolify API now supports database creation through the /api/v1/databases/postgresql endpoint. This allows for fully automated database provisioning without manual intervention.

The user's first prompt to Claude is a high-level instruction to "make a plan" for creating the project and database. This primes the agent to use its extended thinking capabilities.

Prompt: "Claude, I need to deploy a new Node.js application that uses a PostgreSQL database. First, please use the Coolify API to create a new project named 'NodeJS-App'. Then, using the UUID from the newly created project, please provision a PostgreSQL database instance within that project. Document your plan first, then execute it."

Upon receiving this instruction, Claude would:

  1. Make a POST call to the /api/v1/projects endpoint to create the project
  2. Parse the JSON response to extract the project UUID using jq
  3. Make a POST call to /api/v1/databases/postgresql with the project UUID
  4. Extract the database UUID and internal connection URL from the response

Critical requirements for database creation:

  • Use environment_name (e.g., "production") instead of environment_id
  • Provide all required fields: server_uuid, project_uuid, postgres_user, postgres_password, postgres_db
  • Set instant_deploy: true to automatically start the database
  • The response will include internal_db_url which follows the pattern: postgresql://user:password@{db_uuid}:5432/database

Step 2: Configuring the Docker Compose Application

Once the database is provisioned and its connection details have been retrieved, the next step is to create a Docker Compose service that contains the application stack. This involves preparing the docker-compose.yml file and creating the service via the API.

Prompt: "Now, create a Docker Compose service for the application stack. Use the database connection details from the previous step and configure the service with the appropriate environment variables. The docker-compose.yml should include frontend, backend, and database services with proper health checks and networking."

Claude would then perform several critical actions:

  1. Prepare Docker Compose Content: Read the local docker-compose.yml file and validate its structure
  2. Base64 Encode: The docker_compose_raw field requires base64 encoding of the entire compose file
  3. Create Service: Make a POST call to /api/v1/services with the encoded compose content
  4. Configure Networking: Ensure proper service discovery between containers

Key requirements for Docker Compose services:

  • The docker_compose_raw field must be base64 encoded
  • Use environment_name (not environment_id) for consistency
  • Provide server_uuid, project_uuid, and destination_uuid
  • Set instant_deploy: false to allow manual environment configuration before first deployment
  • Health checks in the compose file are essential for proper service monitoring

Common encoding pattern:

DOCKER_COMPOSE_B64=$(cat docker-compose.yml | base64 -w 0)

Step 3: Deploying and Managing the Service

The final step is to start and monitor the Docker Compose service. Unlike single applications, Docker Compose services require different API endpoints for lifecycle management.

Prompt: "The Docker Compose service has been created. Now start the service and monitor its status. Configure environment variables as needed and ensure all containers are healthy before proceeding with database migrations."

This final instruction would prompt Claude to:

  1. Start the Service: Make a POST request to /api/v1/services/{uuid}/start
  2. Monitor Status: Poll /api/v1/services/{uuid} to check overall service status
  3. Check Individual Components: Monitor .applications[].status and .databases[].status in the response
  4. Handle Failures: Use /api/v1/services/{uuid}/restart if containers exit unexpectedly

Critical considerations for service management:

  • Service status can be: running:healthy, running:unhealthy, exited:unhealthy, or individual component states
  • Docker Compose services may take several minutes to build and start all containers
  • Environment variables should be configured before the first start, as they may not be easily updatable via API
  • Health checks defined in the compose file determine the healthy/unhealthy status
  • Use restart instead of stop/start for configuration changes

Service monitoring pattern:

# Check overall service health
curl -s "$COOLIFY_URL/api/v1/services/$SERVICE_UUID" | jq '{status: .status, apps: [.applications[].status], dbs: [.databases[].status]}'

2.0 Troubleshooting, Monitoring, and Best Practices

2.1 Common Errors and Solutions

A robust, expert-level guide must anticipate failure points. An automated deployment can fail for many reasons, but a systematic diagnostic approach can quickly pinpoint the root cause. This section provides a matrix for common Coolify-related errors, turning raw error messages into an actionable troubleshooting guide.

Troubleshooting Matrix for AI-Driven Deployments

Error Type Symptoms Root Cause Diagnosis Steps Solution 502 Bad Gateway 30 The application is accessible via the server IP and port but not the domain. The application is listening on localhost instead of all network interfaces (0.0.0.0) inside the container. Alternatively, port settings are misconfigured. Check the application's listening address in its code (0.0.0.0 is required for containerized apps). Verify the Port Exposes field in the Coolify UI matches the application's internal port. Adjust the application's listening address to 0.0.0.0 and restart. Correct any port misconfigurations. 504 Gateway Timeout 31 The application works initially but fails on long-running requests or after a period of time. A default proxy timeout is too short for large file transfers or complex computations, or the application is using a custom Docker network that the proxy cannot access. Check the Coolify application logs for long-running requests. Examine the Docker Compose file for any custom network definitions. Increase the proxy timeout settings in Coolify's configuration. Alternatively, remove custom network definitions and allow Coolify to manage networking automatically via "Destinations." JavaScript heap out of memory 32 The build process fails with a memory allocation error, or the application crashes after deployment. The Node.js process inside the container is exceeding its allocated memory limit during the build or at runtime. Check server resource usage in the Coolify dashboard.1 Review the application build logs for out of memory errors. Increase server memory or enable swap space. As a targeted solution, add ENV NODE_OPTIONS=--max_old_space_size=2048 to the Dockerfile to allocate more memory to the Node.js process.32 Connection Unstable 33 The server is intermittently reachable, and the connection is frequently lost. A firewall, such as ufw or iptables, is incorrectly configured, often with a LIMIT rule that restricts the number of new connections over a period of time. Use ufw status numbered to inspect the firewall rules.33 Look for rules that limit traffic on the SSH port. Delete the restrictive firewall rule and replace it with a more permissive rule that allows connections without a limit or with a significantly higher limit.33 API Validation Errors API requests return 422 status with validation errors like "environment_id" or "docker_compose_raw should be base64 encoded" Incorrect parameter format or missing required fields in API calls Check API response body for specific validation error messages. Review field requirements in documentation. Use environment_name instead of environment_id. Ensure docker_compose_raw is base64 encoded. Verify all required fields are provided. Service Exited:Unhealthy Docker Compose service shows "exited:unhealthy" status with all containers stopped Missing required environment variables, build failures, or dependency issues in compose file Check individual container logs via Coolify UI. Review environment variable requirements and build context paths. Configure required environment variables before starting. Verify Dockerfile paths and build contexts. Use restart endpoint after fixing configuration. Database Connection Failures Applications cannot connect to database despite correct credentials Network connectivity issues between containers or incorrect database host resolution Verify database container is running and healthy. Check internal network connectivity. Test connection string format. Use database UUID as hostname (e.g., db-uuid:5432) instead of service names. Ensure database is started before dependent services.

2.1.1 API-Specific Troubleshooting

When working with the Coolify API, certain patterns of errors are common and can be systematically addressed:

Environment Variable Issues: The API is strict about field naming. Use environment_name (string) instead of environment_id (integer) for most operations. This is a common source of 422 validation errors.

Docker Compose Encoding: The docker_compose_raw field must be base64 encoded without line wrapping. Use base64 -w 0 on Linux systems to ensure proper encoding.

Service Lifecycle Management: Docker Compose services require different endpoints than single applications. Use /api/v1/services/{uuid}/start instead of deploy endpoints.

Database Internal Networking: When connecting to Coolify-managed databases, use the database UUID as the hostname rather than service names defined in compose files.

2.2 Continuous Workflow Refinement

An advanced aspect of Claude Code's agentic design is its support for "hooks." These are scripts that can be configured to run at specific points during the agent's execution lifecycle, such as before or after a tool is used.8 This capability enables a form of "self-healing" and automated maintenance that goes beyond the initial deployment. For example, a PostToolUse hook could be configured to automatically run a linter or code formatter after the agent writes to a file. This automation ensures that all code written or modified by the agent adheres to project-specific style guides without requiring an explicit prompt for each change. This offloads the responsibility of quality assurance to the agent itself, allowing the developer to focus on the higher-level architecture of the deployment. A PreToolUse hook could also be used to add a security layer, for instance, by preventing the agent from modifying critical files like .env or package-lock.json.34

2.3 Optimizing for Performance and Reliability

For modern application deployments, especially those involving multiple services, performance and reliability considerations extend beyond just memory allocation. The automated deployment process must account for several critical factors.

Build Context and Resource Management: Docker Compose services often require multiple build contexts (frontend, backend, databases). Each service may have different resource requirements during build and runtime. The most common performance issue for Node.js applications remains the "JavaScript heap out of memory" error, which can occur during both build and runtime phases.

To mitigate build-time issues:

  • Set NODE_OPTIONS=--max_old_space_size=2048 in Dockerfiles
  • Use multi-stage builds to reduce final image size
  • Ensure adequate server resources during concurrent service builds

Service Dependencies and Health Checks: Docker Compose services with depends_on conditions require proper health check configuration. Without health checks, dependent services may start before their dependencies are ready, leading to connection failures.

Essential health check patterns:

healthcheck:
  test: ["CMD-SHELL", "pg_isready -U user -d database"]
  interval: 30s
  timeout: 10s
  retries: 3
  start_period: 30s

Network Connectivity in Multi-Service Deployments: Coolify manages container networking automatically, but service-to-service communication requires specific hostname patterns. When connecting to Coolify-managed databases, use the database UUID as the hostname rather than service names defined in compose files.

Environment Variable Management: Unlike single applications, Docker Compose services may not support runtime environment variable updates via API. Plan environment configuration before the first deployment, as changes may require service recreation rather than simple restarts.

Monitoring and Observability: Multi-service deployments require monitoring at multiple levels - individual container health, service-level health, and cross-service connectivity. Implement comprehensive health endpoints that test all critical dependencies, not just basic server responsiveness.

3.0 Conclusion: The Future of AI-Powered Development

The successful completion of this end-to-end deployment guide demonstrates the profound potential of AI agents in modern DevOps. By combining the conversational and reasoning capabilities of a tool like Claude Code with the evolving, programmatic API of a PaaS like Coolify, it is possible to fully automate complex, multi-system deployments with only a series of high-level, natural language prompts.

This blueprint represents a significant evolution from manual deployment processes. The key breakthrough is the agent's ability to adapt to API limitations and inconsistencies - switching between different endpoints, handling validation errors gracefully, and implementing fallback strategies when certain automation paths are blocked.

API Evolution and Adaptation: During real-world deployment, the agent must navigate API inconsistencies, such as field naming conventions (environment_name vs environment_id) and encoding requirements (docker_compose_raw requiring base64). The successful agent demonstrates resilience by detecting these requirements through error responses and adapting its approach accordingly.

Multi-Service Orchestration: Modern applications rarely consist of single services. The agent's ability to manage Docker Compose services - with their complex interdependencies, networking requirements, and lifecycle management - represents a significant advancement in automated deployment capabilities.

Error Recovery and Learning: Real deployments encounter failures. The agent's capacity to analyze error responses, implement fixes, and retry operations demonstrates a level of operational resilience that approaches human problem-solving capabilities.

The programmatic bridge, built with tools like curl and jq, remains critical but has evolved to handle more complex scenarios - database provisioning, service management, and multi-container orchestration. As AI agents become more sophisticated and platforms like Coolify continue to mature their APIs, the entire process will become even more seamless and powerful.

The future of development and operations lies in this collaborative model, where the developer's role shifts from writing low-level, imperative scripts to architecting high-level solutions and entrusting their implementation to a capable AI assistant that can adapt, learn, and recover from failures. While challenges remain - particularly around API consistency and comprehensive documentation - the foundational framework for truly intelligent, adaptive DevOps automation has been clearly established. Works cited Installation | Coolify Docs, accessed September 9, 2025, https://coolify.io/docs/get-started/installation How To Deploy Strapi Application on Coolify Using Docker Compose, accessed September 9, 2025, https://strapi.io/blog/how-to-deploy-strapi-application-on-coolify-using-docker-compose Claude Code: A Guide With Practical Examples | DataCamp, accessed September 9, 2025, https://www.datacamp.com/tutorial/claude-code Claude, accessed September 9, 2025, https://claude.ai/ How to setup a MongoDB replica set with Coolify - Blog, Antonio Gioia, accessed September 9, 2025, https://www.antoniogioia.com/how-to-setup-a-mongodb-replica-set-with-coolify Full HTTPS/TLS Setup for All Resources | Coolify Docs, accessed September 9, 2025, https://coolify.io/docs/knowledge-base/cloudflare/tunnels/full-tls Claude Code Tutorial: How to Generate, Debug and Document ..., accessed September 9, 2025, https://www.codecademy.com/article/claude-code-tutorial-how-to-generate-debug-and-document-code-with-ai Cooking with Claude Code: The Complete Guide - Sid Bharath, accessed September 9, 2025, https://www.siddharthbharath.com/claude-code-the-complete-guide/ Claude Code: Best practices for agentic coding - Anthropic, accessed September 9, 2025, https://www.anthropic.com/engineering/claude-code-best-practices Enable API - Coolify Docs, accessed September 9, 2025, https://coolify.io/docs/api-reference/api/operations/enable-api GET List - API | Coolify Docs, accessed September 9, 2025, https://coolify.io/docs/api-reference/api/operations/list-projects Best Practices for API Key Safety | OpenAI Help Center, accessed September 9, 2025, https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety Using Environment Variables in cURL Command - Unix - Stack Overflow, accessed September 9, 2025, https://stackoverflow.com/questions/31964031/using-environment-variables-in-curl-command-unix How to safely store environmental variables and make it actually invisible in my PC?, accessed September 9, 2025, https://superuser.com/questions/1833341/how-to-safely-store-environmental-variables-and-make-it-actually-invisible-in-my Secure storage of shell secrets such as API keys - Dustin Rue, accessed September 9, 2025, https://dustinrue.com/2025/02/secure-storage-of-shell-secrets-such-as-api-keys/ Storing secrets in env vars considered harmful - Arcjet blog, accessed September 9, 2025, https://blog.arcjet.com/storing-secrets-in-env-vars-considered-harmful/ Securing CI/CD Pipelines with Secrets & Variables - GitHub Resources, accessed September 9, 2025, https://resources.github.com/learn/pathways/automation/advanced/securing-ci-cd-pipelines-with-secrets-and-variables/ Managing Secrets in Your CI/CD Pipeline: Best Practices and Strategies | by Harold Finch, accessed September 9, 2025, https://medium.com/@haroldfinch01/managing-secrets-in-your-ci-cd-pipeline-best-practices-and-strategies-aef0d10e5395 Optimizing Agentic Coding: How I use Claude Code - Research AIMultiple, accessed September 9, 2025, https://research.aimultiple.com/agentic-coding/ Chain complex prompts for stronger performance - Anthropic API, accessed September 9, 2025, https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/chain-prompts How to use jq with curl to explore an API's JSON response - Olivia Coumans, accessed September 9, 2025, https://oliviac.dev/blog/how-to-use-jq-with-curl/ Using jq to fetch key value from json output - Stack Overflow, accessed September 9, 2025, https://stackoverflow.com/questions/39798542/using-jq-to-fetch-key-value-from-json-output POST Create - API | Coolify Docs, accessed September 9, 2025, https://coolify.io/docs/api-reference/api/operations/create-project Bash store json response in another variable - Stack Overflow, accessed September 9, 2025, https://stackoverflow.com/questions/36887134/bash-store-json-response-in-another-variable Coolify Docs, accessed September 9, 2025, https://coolify.io/docs/ GET Deploy - API | Coolify Docs, accessed September 9, 2025, https://coolify.io/docs/api-reference/api/operations/deploy-by-tag-or-uuid List - API | Coolify Docs, accessed September 9, 2025, https://coolify.io/docs/api-reference/api/operations/list-deployments run prisma studio on coolify database - Wasp - Answer Overflow, accessed September 9, 2025, https://www.answeroverflow.com/m/1404604292513533982 Environment Variables | Coolify Docs, accessed September 9, 2025, https://coolify.io/docs/knowledge-base/environment-variables Bad Gateway Error | Coolify Docs, accessed September 9, 2025, https://coolify.io/docs/troubleshoot/applications/bad-gateway Gateway Timeout (504) Errors - Coolify, accessed September 9, 2025, https://coolify.io/docs/troubleshoot/applications/gateway-timeout JavaScript heap out of memory in Docker image run - Stack Overflow, accessed September 9, 2025, https://stackoverflow.com/questions/67903114/javascript-heap-out-of-memory-in-docker-image-run Connection Unstable | Coolify Docs, accessed September 9, 2025, https://coolify.io/docs/troubleshoot/server/connection-issues Get started with Claude Code hooks - Anthropic API, accessed September 9, 2025, https://docs.anthropic.com/en/docs/claude-code/hooks-guide

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors