> ## Documentation Index
> Fetch the complete documentation index at: https://www.qovery.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Deploy a Go Application

> Deploy a Go web service with PostgreSQL on Kubernetes in your own cloud account with Qovery: multi-stage Dockerfile with a distroless image, port and health check, golang-migrate migrations as a lifecycle job.

This guide deploys a Go web service built with `net/http`, with a PostgreSQL database and migrations that run before each release. Qovery builds the image from your Dockerfile and runs it on a Kubernetes cluster in your own cloud account.

> [!NOTE]
>
> **No configuration file in your repository.** Qovery does not read a `qovery.yml`, `.qovery.yml` or `.qovery.toml`, and there is no `qovery init`. Projects, environments and services are created in the Console, with `qovery api`, or with [Terraform](https://www.qovery.com/docs/terraform-provider/overview.md). For the full path from a repository to a running app with commands only, see [Deploy with the CLI and API](https://www.qovery.com/docs/getting-started/quickstart/cli-and-api.md).

## Prerequisites

* A Go module in a GitHub, GitLab or Bitbucket repository, with a `go.mod` and a `go.sum`.
* A Qovery account and a cluster: [create one in your cloud account](https://www.qovery.com/docs/getting-started/quickstart/cloud.md), [connect your own cluster](https://www.qovery.com/docs/getting-started/installation/kubernetes.md), or [try it on your laptop](https://www.qovery.com/docs/getting-started/quickstart/try-with-an-agent.md).
* These modules in `go.mod`: `github.com/jackc/pgx/v5` and `github.com/golang-migrate/migrate/v4`.

## Prepare the server

Listen on the port from `PORT`, answer a health check, read the database URL from the environment, and add a `migrate` subcommand that applies the migrations embedded in the binary:

```go main.go theme={null}
package main

import (
	"context"
	"embed"
	"errors"
	"log"
	"net/http"
	"os"
	"strings"

	"github.com/golang-migrate/migrate/v4"
	_ "github.com/golang-migrate/migrate/v4/database/pgx/v5"
	"github.com/golang-migrate/migrate/v4/source/iofs"
	"github.com/jackc/pgx/v5/pgxpool"
)

//go:embed migrations/*.sql
var migrations embed.FS

func main() {
	databaseURL := os.Getenv("DATABASE_URL")

	if len(os.Args) > 1 && os.Args[1] == "migrate" {
		if err := runMigrations(databaseURL); err != nil {
			log.Fatal(err)
		}
		log.Println("migrations applied")
		return
	}

	pool, err := pgxpool.New(context.Background(), databaseURL)
	if err != nil {
		log.Fatal(err)
	}
	defer pool.Close()

	http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok"))
	})

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("listening on %s", port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}

func runMigrations(databaseURL string) error {
	source, err := iofs.New(migrations, "migrations")
	if err != nil {
		return err
	}
	// The pgx/v5 driver of golang-migrate reads URLs that start with pgx5://
	m, err := migrate.NewWithSourceInstance("iofs", source, strings.Replace(databaseURL, "postgresql://", "pgx5://", 1))
	if err != nil {
		return err
	}
	if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
		return err
	}
	return nil
}
```

`":"+port` listens on all interfaces, so Kubernetes can reach the server. Put the migrations in a `migrations` folder next to `main.go`, in the golang-migrate file format, for example `000001_create_items.up.sql` and `000001_create_items.down.sql`. `//go:embed` compiles them into the binary, so the image needs no other file.

## Add a production Dockerfile

Create a `Dockerfile` at the root of the repository:

```dockerfile Dockerfile theme={null}
FROM golang:1.27-alpine AS build

WORKDIR /src

COPY go.mod go.sum ./
RUN go mod download

COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server .

FROM gcr.io/distroless/static-debian13:nonroot

COPY --from=build /out/server /server

ENV PORT=8080
EXPOSE 8080
USER nonroot:nonroot
CMD ["/server"]
```

* The first stage compiles with the official `golang:1.27-alpine` image. Match the Go version to the `go` line of your `go.mod`.
* Copying `go.mod` and `go.sum` before the code keeps the downloaded modules cached when only the code changes.
* `CGO_ENABLED=0` builds a static binary, which runs without a C library. `-trimpath` and `-ldflags="-s -w"` remove local paths and debug symbols.
* The final image, `gcr.io/distroless/static-debian13:nonroot`, holds only the binary, CA certificates and time zone data, with no shell. It runs as a non-root user.
* `CMD ["/server"]` starts the binary directly, so it receives the stop signal.

Add a `.dockerignore` with at least `.git` to keep the build context small.

## Port and health check

The application listens on port `8080` and answers `GET /healthz` with `200`. Use both values when you create the application in Qovery.

## Connect PostgreSQL

The application and the migration job read the connection string from `DATABASE_URL`. Create PostgreSQL, then expose its connection string under that name at the environment scope, so every service of the environment gets it.

> [tab] Qovery database (development)
>
> 1. In the environment, click **New Service** and pick **PostgreSQL**. Keep the visibility private, then create and deploy it. See [Create a Database](https://www.qovery.com/docs/getting-started/guides/getting-started/connect-database.md).
> 2. Open the **Variables** section of the environment, find the built-in variable `QOVERY_POSTGRESQL_Z<ID>_DATABASE_URL_INTERNAL`, select **Create alias**, and name it `DATABASE_URL`.
>
> From the CLI, once the application exists:
>
> ```bash theme={null} theme={null} theme={null} theme={null} theme={null}
> # Copy the exact name of the ..._DATABASE_URL_INTERNAL variable
> qovery application env list -n my-app
>
> qovery application env alias create -n my-app \
>   -k "QOVERY_POSTGRESQL_Z1234ABCD_DATABASE_URL_INTERNAL" \
>   --alias DATABASE_URL --scope ENVIRONMENT
> ```
>
> This database runs as a container on your cluster, with no automated backups. Use it for development and testing.

> [tab] Blueprint (production)
>
> 1. In the environment, click **New Service** › **Blueprint** and pick a managed PostgreSQL, such as [Amazon RDS for PostgreSQL](https://www.qovery.com/docs/configuration/blueprints/aws-rds-postgresql.md) or [Scaleway Managed PostgreSQL](https://www.qovery.com/docs/configuration/blueprints/scaleway-managed-postgresql.md). Deploy it.
> 2. The Blueprint publishes its outputs as variables named `QOVERY_OUTPUT_TERRAFORM_Z<ID>_<OUTPUT>`, and by default Qovery also creates an alias for each output, named `<PREFIX>_<OUTPUT>` after the Blueprint name. See [Aliases Qovery creates for outputs](https://www.qovery.com/docs/configuration/environment-variables.md#aliases-qovery-creates-for-outputs) for the naming rules and the cases where no alias is created. Copy the prefix from the **Variables** section, then create an environment secret `DATABASE_URL` that composes the outputs with `{{...}}` interpolation. The output names differ per Blueprint.
>
> Amazon RDS for PostgreSQL:
>
> ```text theme={null} theme={null} theme={null} theme={null} theme={null}
> postgresql://{{QOVERY_OUTPUT_TERRAFORM_Z1234ABCD_DB_USERNAME}}:{{QOVERY_OUTPUT_TERRAFORM_Z1234ABCD_DB_PASSWORD}}@{{QOVERY_OUTPUT_TERRAFORM_Z1234ABCD_DB_ADDRESS}}:{{QOVERY_OUTPUT_TERRAFORM_Z1234ABCD_DB_PORT}}/{{QOVERY_OUTPUT_TERRAFORM_Z1234ABCD_DB_NAME}}
> ```
>
> Scaleway Managed PostgreSQL:
>
> ```text theme={null} theme={null} theme={null} theme={null} theme={null}
> postgresql://{{QOVERY_OUTPUT_TERRAFORM_Z1234ABCD_DB_USERNAME}}:{{QOVERY_OUTPUT_TERRAFORM_Z1234ABCD_DB_PASSWORD}}@{{QOVERY_OUTPUT_TERRAFORM_Z1234ABCD_ENDPOINT_IP}}:{{QOVERY_OUTPUT_TERRAFORM_Z1234ABCD_ENDPOINT_PORT}}/{{QOVERY_OUTPUT_TERRAFORM_Z1234ABCD_DB_NAME}}
> ```
>
> Interpolation inserts the values as they are, without URL encoding. Leave the Blueprint's `db_password` input empty so Qovery generates the password, or set one made of letters and digits only: characters such as `#`, `?`, `%` or `:` break the URL.
>
> Make sure the Blueprint is deployed in a [deployment stage](https://www.qovery.com/docs/configuration/deployment/pipeline.md) that runs before the migration job.

See [Aliases](https://www.qovery.com/docs/configuration/environment-variables.md#aliases) and [Variable Interpolation](https://www.qovery.com/docs/configuration/environment-variables.md#variable-interpolation) for the rules.

pgx reads the `postgresql://` URL as is. The `migrate` subcommand only swaps its scheme for `pgx5://`, the name the golang-migrate pgx driver registers.

## Set the variables

| Variable | Value | Secret |
| - | - | - |
| `DATABASE_URL` | The alias or secret from [Connect PostgreSQL](#connect-postgresql) | Yes |

Add the other variables your application reads, and mark keys and passwords as secrets.

## Run the migrations

Run the `migrate` subcommand in a [lifecycle job](https://www.qovery.com/docs/configuration/lifecycle-job.md) built from the same repository and Dockerfile, triggered on the **Deploy** event, with these CMD arguments:

```json theme={null}
["/server", "migrate"]
```

The job runs once per deployment. In the default [deployment pipeline](https://www.qovery.com/docs/configuration/deployment/pipeline.md), jobs run after the databases and before the applications, so the schema is up to date when the new code starts. golang-migrate records the applied version in a `schema_migrations` table, so a run with nothing new exits successfully.

Running the migrations at server startup instead works for a single instance, but every instance then runs them at boot, and a failed migration leaves the application crashing in a loop.

## Deploy

> [tab] Console
>
> **1. Create a project and an environment**
>
> Follow steps 1 and 2 of [Deploy Your First Application](https://www.qovery.com/docs/getting-started/guides/getting-started/deploy-your-first-application.md#step-1-create-a-project). Pick the cluster the environment runs on.
>
> **2. Add PostgreSQL**
>
> Create the database and the `DATABASE_URL` variable as described in [Connect PostgreSQL](#connect-postgresql).
>
> **3. Create the application**
>
> In the environment, click **New Service** › **Create application**, select **Git Repository**, then your repository and branch. Leave **Root Application Path** empty unless the Dockerfile is in a subfolder.
>
> **4. Set the port**
>
> Add port `8080` with the protocol **HTTP**, and turn on **Publicly Accessible**. Qovery serves it over HTTPS on port 443.
>
> **5. Set the health checks**
>
> Set the readiness and liveness probes to type **HTTP**, path `/healthz`, port `8080`. See [Service Health Checks](https://www.qovery.com/docs/configuration/service-health-checks.md).
>
> **6. Add the variables**
>
> Click **Create**, without deploying yet. Then open the **Variables** section of the environment and add the other variables listed in [Set the variables](#set-the-variables) at the environment scope, so the migration job gets them too. `DATABASE_URL` already exists from the previous step. Mark keys and passwords as secrets.
>
> **7. Create the migration job**
>
> Click **New Service** › **Create lifecycle job**, select the same repository, branch and Dockerfile, and trigger it on the **Deploy** event (`START`) with the CMD arguments `["/server", "migrate"]`. Set the number of restarts to 0. See [Run the migrations](#run-the-migrations).
>
> **8. Deploy**
>
> Deploy the environment. Qovery deploys the database, then the job, then the application, builds the image from your Dockerfile and gives the application a URL on `qovery.io`. Follow the progress in the **Deployment logs** tab.

> [tab] With a coding agent
>
> Install the Qovery skills once:
>
> ```bash theme={null}
> curl -fsSL https://skill.qovery.com/install.sh | bash
> ```
>
> Open your agent in the repository and paste:
>
> claude
>
> Copy
>
> Deploy this Go service with Qovery, with a PostgreSQL database and a lifecycle job that runs the migrations.
>
> The agent writes the Dockerfile if there is none, creates the database, the variables, the job and the application, and gives you the URL. See [Agent Skills](https://www.qovery.com/docs/getting-started/quickstart/agent-skills.md).

## Troubleshooting

The CLI commands below use the organization, project and environment selected with `qovery context set`. Run it first, or add `--organization`, `--project` and `--environment` to each command.

> [accordion] Deployment fails on the health check
>
> The server listens on another port than the one set in Qovery, or on `127.0.0.1`. Listen on `":"+port` and check that the port in Qovery is `8080`. Read the error lines with `qovery environment deployment logs --environment "<env>" --service "<app>" --errors-only`.

> [accordion] no such file or directory at startup
>
> The binary was built with cgo, so it needs a C library that the distroless `static` image does not have. Keep `CGO_ENABLED=0`. If a dependency needs cgo, use `gcr.io/distroless/base-debian13:nonroot` as the final image instead.

> [accordion] relation does not exist
>
> The migrations did not run against this database. Check that the job and the application read the same `DATABASE_URL` at the environment scope, and read the job output with `qovery log --job "<job name>"`.

> [accordion] Dirty database version
>
> A migration failed halfway, and golang-migrate refuses to run until the version is fixed. Correct the migration, then set the version back with the [migrate CLI](https://github.com/golang-migrate/migrate/tree/master/cmd/migrate) `force` command against the database, and redeploy.

For other errors, see [Diagnose a Failed Build or Deployment](https://www.qovery.com/docs/getting-started/troubleshoot/overview.md#diagnose-a-failed-build-or-deployment).

## Next steps

> [card] [Preview environments](https://www.qovery.com/docs/getting-started/guides/use-cases/preview-environments.md)
>
> Get a full copy of the environment for each pull request

> [card] [Autoscaling](https://www.qovery.com/docs/configuration/application.md)
>
> Set the number of instances and the resources

> [card] [Auto deploy](https://www.qovery.com/docs/configuration/deployment/auto-deploy.md)
>
> Deploy on every push to the branch

> [card] [Other frameworks](https://www.qovery.com/docs/getting-started/guides/frameworks/overview.md)
>
> All framework guides


## Related topics

- [Deploy Your First Application](https://www.qovery.com/docs/getting-started/guides/getting-started/deploy-your-first-application.md)
- [Deploy application](https://www.qovery.com/docs/api-reference/application-actions/deploy-application.md)
- [Certificate Management for Multi-Tenant Applications](https://www.qovery.com/docs/getting-started/guides/advanced-tutorials/certificate-management-multi-tenant.md)
- [Deploy a Django Application](https://www.qovery.com/docs/getting-started/guides/frameworks/django.md)
- [Deploy a Laravel Application](https://www.qovery.com/docs/getting-started/guides/frameworks/laravel.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.