diff --git a/docs/how-to/self-host.md b/docs/how-to/self-host.md index 4523d81309..3715db2f27 100644 --- a/docs/how-to/self-host.md +++ b/docs/how-to/self-host.md @@ -1,8 +1,7 @@ --- -seotitle: Self-hosted Encore deployments -seodesc: Learn how to self-host your Encore applications, using Encore's open-source tooling. -title: Self-hosted Encore deployments -subtitle: Deploy your Encore application to your own infrastructure, using Encore's open-source tooling. +seotitle: Build Docker Images +seodesc: Learn how to build Docker images for your Encore application, which can be self-hosted on your own infrastructure. +title: Build Docker Images --- Encore supports building Docker images directly from the CLI, which can then be self-hosted on your own infrastructure of choice. @@ -29,428 +28,5 @@ The image will default to run on port 8080, but you can customize it by setting docker run -e PORT=8081 -p 8081:8081 MY-IMAGE:TAG ``` -## Configuring your Docker image - -If you are using infrastructure resources, such as SQL databases, Pub/Sub, or metrics, you will need to configure your Docker image with the necessary configuration. -The `build` command lets you provide this by specifying a path to a config file using the `--config` flag. - -```bash -encore build docker --config path/to/infra-config.json MY-IMAGE:TAG -``` - -The configuration file should be a JSON file using the [Encore Infra Config](https://encore.dev/schemas/infra.schema.json) schema. - -This includes configuring things like: - -- How to access infrastructure resources (what provider to use, what credentials to use, etc.) -- How to call other services over the network ("service discovery"), - most notably their base URLs. -- Observability configuration (where to export metrics, etc.) -- Metadata about the environment the application is running in, to power Encore's [metadata APIs](/docs/develop/metadata). -- The values for any application-defined secrets. - -This configuration is necessary for the application to behave correctly. - -## Example - -Here's an example configuration file you can use. - -```json -{ - "$schema": "https://encore.dev/schemas/infra.schema.json", - "metadata": { - "app_id": "my-app", - "env_name": "my-env", - "env_type": "production", - "cloud": "gcp", - "base_url": "https://my-app.com" - }, - "sql_servers": [ - { - "host": "my-db-host:5432", - "databases": { - "my-db": { - "username": "my-db-owner", - "password": {"$env": "DB_PASSWORD"} - } - } - } - ], - "service_discovery": { - "myservice": { - "base_url": "https://my-service:8044" - } - }, - "redis": { - "encoreredis": { - "database_index": 0, - "auth": { - "type": "acl", - "username": "encoreredis", - "password": {"$env": "REDIS_PASSWORD"} - }, - "host": "my-redis-host", - } - }, - "metrics": { - "type": "prometheus", - "remote_write_url": "https://my-remote-write-url" - }, - "graceful_shutdown": { - "total": 30 - }, - "auth": [ - { - "type": "key", - "id": 1, - "key": {"$env": "SVC_TO_SVC_KEY"} - } - ], - "secrets": { - "AppSecret": {"$env": "APP_SECRET"} - }, - "pubsub": [ - { - "type": "gcp_pubsub", - "project_id": "my-project", - "topics": { - "encore-topic": { - "name": "gcp-topic-name", - "subscriptions": { - "encore-subscription": { - "name": "gcp-subscription-name" - } - } - } - } - } - ] -} -``` - -## Configuring Infrastructure -To use infrastructure resources, additional configuration must be added so that Encore is aware of how to access each infrastructure resource. -See below for examples of each type of infrastructure resource. - -### 1. Basic Environment Metadata Configuration - -```json -{ - "metadata": { - "app_id": "my-encore-app", - "env_name": "production", - "env_type": "production", - "cloud": "aws", - "base_url": "https://api.myencoreapp.com" - } -} -``` - -- `app_id`: The ID of your Encore application. -- `env_name`: The environment name, such as `production`, `staging`, or `development`. -- `env_type`: Specifies the type of environment (`production`, `test`, `development`, or `ephemeral`). -- `cloud`: The cloud provider hosting the infrastructure (e.g., `aws`, `gcp`, or `azure`). -- `base_url`: The base URL for services in the environment. - -### 2. Graceful Shutdown Configuration - -```json -{ - "graceful_shutdown": { - "total": 30, - "shutdown_hooks": 10, - "handlers": 20 - } -} -``` - -- `total`: The total time allowed for the shutdown process in seconds. -- `shutdown_hooks`: The time allowed for executing shutdown hooks. -- `handlers`: The time allocated for processing request handlers during the shutdown. - -### 3. Authentication Methods Configuration -Private endpoints will not require authentication if no authentication methods are specified. To secure private endpoints, you can configure authentication methods. -Encore currently supports authentication through a shared key, which you can specify in your infrastructure configuration file. -```json -{ - "auth": [ - { - "type": "key", - "id": 1, - "key": { - "$env": "SERVICE_API_KEY" - } - } - ] -} -``` - -- `type`: The authentication method type (e.g., `key`). -- `id`: The ID associated with the authentication method. -- `key`: The authentication key, which can be set using an environment variable reference. - -### 4. Service Discovery Configuration -Service discovery is used to access other services over the network. You can configure service discovery in the infrastructure configuration file. -If you export all services into the same docker image, you don't need to configure service discovery as it will be automatically -configured when the services are started. - -```json -{ - "service_discovery": { - "user-service": { - "base_url": "https://user.myencoreapp.com", - "auth": [ - { - "type": "key", - "id": 1, - "key": { - "$env": "USER_SERVICE_API_KEY" - } - } - ] - } - } -} -``` - -- `user-service`: Configuration for a service named `user-service`. -- `base_url`: The base URL for the service. -- `auth`: Authentication methods used for accessing the service. If no authentication methods are specified, the service will use the auth methods defined in the `auth` section. - -### 5. Metrics Configuration -Similarly to cloud infrastructure resources, Encore supports configurable metrics exports: - -* Prometheus -* DataDog -* GCP Cloud Monitoring -* AWS CloudWatch - -This is configured by setting the metrics field. Below are examples for each of the supported metrics providers: -#### 5.1. Prometheus Configuration - -```json -{ - "metrics": { - "type": "prometheus", - "collection_interval": 15, - "remote_write_url": { - "$env": "PROMETHEUS_REMOTE_WRITE_URL" - } - } -} -``` - -#### 5.2. Datadog Configuration - -```json -{ - "metrics": { - "type": "datadog", - "collection_interval": 30, - "site": "datadoghq.com", - "api_key": { - "$env": "DATADOG_API_KEY" - } - } -} -``` - -#### 5.3. GCP Cloud Monitoring Configuration - -```json -{ - "metrics": { - "type": "gcp_cloud_monitoring", - "collection_interval": 60, - "project_id": "my-gcp-project", - "monitored_resource_type": "gce_instance", - "monitored_resource_labels": { - "instance_id": "1234567890", - "zone": "us-central1-a" - }, - "metric_names": { - "cpu_usage": "compute.googleapis.com/instance/cpu/usage_time" - } - } -} -``` - -#### 5.4. AWS CloudWatch Configuration - -```json -{ - "metrics": { - "type": "aws_cloudwatch", - "collection_interval": 60, - "namespace": "MyAppMetrics" - } -} -``` - -### 6. SQL Database Configuration -The SQL databases you've declared in your Encore app must be configured in the infrastructure configuration file. -There must be exactly one database configuration for each declared database. You can configure multiple SQL servers if needed. - -```json -{ - "sql_servers": [ - { - "host": "db.myencoreapp.com:5432", - "tls_config": { - "disabled": false, - "ca": "---BEGIN CERTIFICATE---\n..." - }, - "databases": { - "main_db": { - "max_connections": 100, - "min_connections": 10, - "username": "db_user", - "password": { - "$env": "DB_PASSWORD" - } - } - } - } - ] -} -``` - -- `host`: SQL server host, optionally including the port. -- `tls_config`: TLS configuration for secure connections. If the server uses TLS with a non-system CA root, or requires a client certificate, specify the appropriate fields as PEM-encoded strings. Otherwise, they can be left empty. -- `databases`: List of databases, each with connection settings. - -### 7. Secrets Configuration - -#### 7.1. Using Direct Secrets -You can set the secret value directly in the configuration file, or use an environment variable reference to set the secret value. - -```json -{ - "secrets": { - "API_TOKEN": "embedded-secret-value", - "DB_PASSWORD": { - "$env": "DB_PASSWORD" - } - } -} -``` - -#### 7.2. Using Environment Reference -As an alternative, you can use an environment variable reference to set the secret value. The env variable should be set in the environment where the application is running. The content -of the environment variable should be a JSON string where each key is the secret name and the value is the secret value. - -```json -{ - "secrets": { - "$env": "SECRET_JSON" - } -} -``` - -### 8. Redis Configuration - -```json -{ - "redis": { - "cache": { - "host": "redis.myencoreapp.com:6379", - "database_index": 0, - "auth": { - "type": "auth", - "auth_string": { - "$env": "REDIS_AUTH_STRING" - } - }, - "max_connections": 50, - "min_connections": 5 - } - } -} -``` - -- `host`: Redis server host, optionally including the port. -- `auth`: Authentication configuration for the Redis server. -- `key_prefix`: Prefix applied to all keys. - -### 9. Pub/Sub Configuration -Encore currently supports the following Pub/Sub providers: -- `nsq` for [NSQ](https://nsq.io/) -- `gcp` for [Google Cloud Pub/Sub](https://cloud.google.com/pubsub) -- `aws` for AWS [SNS](https://aws.amazon.com/sns/) + [SQS](https://aws.amazon.com/sqs/) -- `azure` for [Azure Service Bus](https://azure.microsoft.com/en-us/products/service-bus) - -The configuration for each provider is different. Below are examples for each provider. -#### 9.1. GCP Pub/Sub - -```json -{ - "pubsub": [ - { - "type": "gcp_pubsub", - "project_id": "my-gcp-project", - "topics": { - "user-events": { - "name": "user-events-topic", - "project_id": "my-gcp-project", - "subscriptions": { - "user-notification": { - "name": "user-notification-subscription", - "push_config": { - "id": "user-push", - "service_account": "service-account@my-gcp-project.iam.gserviceaccount.com" - } - } - } - } - } - } - ] -} -``` - -#### 9.2. AWS SNS/SQS - -```json -{ - "pubsub": [ - { - "type": "aws_sns_sqs", - "topics": { - "user-notifications": { - "arn": "arn:aws:sns:us-east-1:123456789012:user-notifications", - "subscriptions": { - "user-queue": { - "arn": "arn:aws:sqs:us-east-1:123456789012:user-queue" - } - } - } - } - } - ] -} -``` - -#### 9.3. NSQ Configuration - -```json -{ - "pubsub": [ - { - "type": "nsq", - "hosts": "nsq.myencoreapp.com:4150", - "topics": { - "order-events": { - "name": "order-events-topic", - "subscriptions": { - "order-processor": { - "name": "order-processor-subscription" - } - } - } - } - } - ] -} -``` - -This guide covers typical infrastructure configurations. Adjust according to your specific requirements to optimize your Encore app's infrastructure setup. \ No newline at end of file +Congratulations, you've built your own Docker image! 🎉 +Continue to learn how to [configure infrastructure](/docs/selfhosting/configure-infra). \ No newline at end of file diff --git a/docs/menu.cue b/docs/menu.cue index efed95ba36..d0cf93e3f9 100644 --- a/docs/menu.cue +++ b/docs/menu.cue @@ -106,6 +106,7 @@ #DevelopmentSection, #ObservabilitySection, #PlatformSection, + #SelfHostingSection, #ResourcesSection, #CommunitySection, #OtherSection, @@ -745,6 +746,28 @@ }] } +#SelfHostingSection: #SectionMenuItem & { + kind: "section" + text: "Self Hosting" + items: [ + { + kind: "basic" + text: "Build Docker Images" + path: "/how-to/self-host" + file: "how-to/self-host" + }, { + kind: "basic" + text: "Configure Infrastructure" + path: "/selfhosting/configure-infra" + file: "selfhosting/configure-infra" + }, { + kind: "basic" + text: "Deploy to DigitalOcean" + path: "/selfhosting/deploy-digitalocean" + file: "selfhosting/deploy-to-digital-ocean" + }] +} + #ResourcesSection: #SectionMenuItem & { kind: "section" text: "Resources" @@ -781,11 +804,6 @@ text: "Use Temporal with Encore" path: "/how-to/temporal" file: "how-to/temporal" - }, { - kind: "basic" - text: "Self-host Encore applications" - path: "/how-to/self-host" - file: "how-to/self-host" }, { kind: "basic" text: "Submit a Template" diff --git a/docs/selfhosting/configure-infra.md b/docs/selfhosting/configure-infra.md new file mode 100644 index 0000000000..9808ec2be2 --- /dev/null +++ b/docs/selfhosting/configure-infra.md @@ -0,0 +1,429 @@ +--- +title: Configure Infrastructure +seotitle: Configure Infrastructure +seodesc: Learn how to configure infrastructure resources for your Encore app. +--- + +If you are using infrastructure resources, such as SQL databases, Pub/Sub, or metrics, you will need to configure your Docker image with the necessary configuration. +The `build` command lets you provide this by specifying a path to a config file using the `--config` flag. + +```bash +encore build docker --config path/to/infra-config.json MY-IMAGE:TAG +``` + +The configuration file should be a JSON file using the [Encore Infra Config](https://encore.dev/schemas/infra.schema.json) schema. + +This includes configuring things like: + +- How to access infrastructure resources (what provider to use, what credentials to use, etc.) +- How to call other services over the network ("service discovery"), + most notably their base URLs. +- Observability configuration (where to export metrics, etc.) +- Metadata about the environment the application is running in, to power Encore's [metadata APIs](/docs/develop/metadata). +- The values for any application-defined secrets. + +This configuration is necessary for the application to behave correctly. + +## Example + +Here's an example configuration file you can use. + +```json +{ + "$schema": "https://encore.dev/schemas/infra.schema.json", + "metadata": { + "app_id": "my-app", + "env_name": "my-env", + "env_type": "production", + "cloud": "gcp", + "base_url": "https://my-app.com" + }, + "sql_servers": [ + { + "host": "my-db-host:5432", + "databases": { + "my-db": { + "username": "my-db-owner", + "password": {"$env": "DB_PASSWORD"} + } + } + } + ], + "service_discovery": { + "myservice": { + "base_url": "https://my-service:8044" + } + }, + "redis": { + "encoreredis": { + "database_index": 0, + "auth": { + "type": "acl", + "username": "encoreredis", + "password": {"$env": "REDIS_PASSWORD"} + }, + "host": "my-redis-host", + } + }, + "metrics": { + "type": "prometheus", + "remote_write_url": "https://my-remote-write-url" + }, + "graceful_shutdown": { + "total": 30 + }, + "auth": [ + { + "type": "key", + "id": 1, + "key": {"$env": "SVC_TO_SVC_KEY"} + } + ], + "secrets": { + "AppSecret": {"$env": "APP_SECRET"} + }, + "pubsub": [ + { + "type": "gcp_pubsub", + "project_id": "my-project", + "topics": { + "encore-topic": { + "name": "gcp-topic-name", + "subscriptions": { + "encore-subscription": { + "name": "gcp-subscription-name" + } + } + } + } + } + ] +} +``` + +## Configuring Infrastructure +To use infrastructure resources, additional configuration must be added so that Encore is aware of how to access each infrastructure resource. +See below for examples of each type of infrastructure resource. + +### 1. Basic Environment Metadata Configuration + +```json +{ + "metadata": { + "app_id": "my-encore-app", + "env_name": "production", + "env_type": "production", + "cloud": "aws", + "base_url": "https://api.myencoreapp.com" + } +} +``` + +- `app_id`: The ID of your Encore application. +- `env_name`: The environment name, such as `production`, `staging`, or `development`. +- `env_type`: Specifies the type of environment (`production`, `test`, `development`, or `ephemeral`). +- `cloud`: The cloud provider hosting the infrastructure (e.g., `aws`, `gcp`, or `azure`). +- `base_url`: The base URL for services in the environment. + +### 2. Graceful Shutdown Configuration + +```json +{ + "graceful_shutdown": { + "total": 30, + "shutdown_hooks": 10, + "handlers": 20 + } +} +``` + +- `total`: The total time allowed for the shutdown process in seconds. +- `shutdown_hooks`: The time allowed for executing shutdown hooks. +- `handlers`: The time allocated for processing request handlers during the shutdown. + +### 3. Authentication Methods Configuration +Private endpoints will not require authentication if no authentication methods are specified. To secure private endpoints, you can configure authentication methods. +Encore currently supports authentication through a shared key, which you can specify in your infrastructure configuration file. +```json +{ + "auth": [ + { + "type": "key", + "id": 1, + "key": { + "$env": "SERVICE_API_KEY" + } + } + ] +} +``` + +- `type`: The authentication method type (e.g., `key`). +- `id`: The ID associated with the authentication method. +- `key`: The authentication key, which can be set using an environment variable reference. + +### 4. Service Discovery Configuration +Service discovery is used to access other services over the network. You can configure service discovery in the infrastructure configuration file. +If you export all services into the same docker image, you don't need to configure service discovery as it will be automatically +configured when the services are started. + +```json +{ + "service_discovery": { + "user-service": { + "base_url": "https://user.myencoreapp.com", + "auth": [ + { + "type": "key", + "id": 1, + "key": { + "$env": "USER_SERVICE_API_KEY" + } + } + ] + } + } +} +``` + +- `user-service`: Configuration for a service named `user-service`. +- `base_url`: The base URL for the service. +- `auth`: Authentication methods used for accessing the service. If no authentication methods are specified, the service will use the auth methods defined in the `auth` section. + +### 5. Metrics Configuration +Similarly to cloud infrastructure resources, Encore supports configurable metrics exports: + +* Prometheus +* DataDog +* GCP Cloud Monitoring +* AWS CloudWatch + +This is configured by setting the metrics field. Below are examples for each of the supported metrics providers: +#### 5.1. Prometheus Configuration + +```json +{ + "metrics": { + "type": "prometheus", + "collection_interval": 15, + "remote_write_url": { + "$env": "PROMETHEUS_REMOTE_WRITE_URL" + } + } +} +``` + +#### 5.2. Datadog Configuration + +```json +{ + "metrics": { + "type": "datadog", + "collection_interval": 30, + "site": "datadoghq.com", + "api_key": { + "$env": "DATADOG_API_KEY" + } + } +} +``` + +#### 5.3. GCP Cloud Monitoring Configuration + +```json +{ + "metrics": { + "type": "gcp_cloud_monitoring", + "collection_interval": 60, + "project_id": "my-gcp-project", + "monitored_resource_type": "gce_instance", + "monitored_resource_labels": { + "instance_id": "1234567890", + "zone": "us-central1-a" + }, + "metric_names": { + "cpu_usage": "compute.googleapis.com/instance/cpu/usage_time" + } + } +} +``` + +#### 5.4. AWS CloudWatch Configuration + +```json +{ + "metrics": { + "type": "aws_cloudwatch", + "collection_interval": 60, + "namespace": "MyAppMetrics" + } +} +``` + +### 6. SQL Database Configuration +The SQL databases you've declared in your Encore app must be configured in the infrastructure configuration file. +There must be exactly one database configuration for each declared database. You can configure multiple SQL servers if needed. + +```json +{ + "sql_servers": [ + { + "host": "db.myencoreapp.com:5432", + "tls_config": { + "disabled": false, + "ca": "---BEGIN CERTIFICATE---\n..." + }, + "databases": { + "main_db": { + "max_connections": 100, + "min_connections": 10, + "username": "db_user", + "password": { + "$env": "DB_PASSWORD" + } + } + } + } + ] +} +``` + +- `host`: SQL server host, optionally including the port. +- `tls_config`: TLS configuration for secure connections. If the server uses TLS with a non-system CA root, or requires a client certificate, specify the appropriate fields as PEM-encoded strings. Otherwise, they can be left empty. +- `databases`: List of databases, each with connection settings. + +### 7. Secrets Configuration + +#### 7.1. Using Direct Secrets +You can set the secret value directly in the configuration file, or use an environment variable reference to set the secret value. + +```json +{ + "secrets": { + "API_TOKEN": "embedded-secret-value", + "DB_PASSWORD": { + "$env": "DB_PASSWORD" + } + } +} +``` + +#### 7.2. Using Environment Reference +As an alternative, you can use an environment variable reference to set the secret value. The env variable should be set in the environment where the application is running. The content +of the environment variable should be a JSON string where each key is the secret name and the value is the secret value. + +```json +{ + "secrets": { + "$env": "SECRET_JSON" + } +} +``` + +### 8. Redis Configuration + +```json +{ + "redis": { + "cache": { + "host": "redis.myencoreapp.com:6379", + "database_index": 0, + "auth": { + "type": "auth", + "auth_string": { + "$env": "REDIS_AUTH_STRING" + } + }, + "max_connections": 50, + "min_connections": 5 + } + } +} +``` + +- `host`: Redis server host, optionally including the port. +- `auth`: Authentication configuration for the Redis server. +- `key_prefix`: Prefix applied to all keys. + +### 9. Pub/Sub Configuration +Encore currently supports the following Pub/Sub providers: +- `nsq` for [NSQ](https://nsq.io/) +- `gcp` for [Google Cloud Pub/Sub](https://cloud.google.com/pubsub) +- `aws` for AWS [SNS](https://aws.amazon.com/sns/) + [SQS](https://aws.amazon.com/sqs/) +- `azure` for [Azure Service Bus](https://azure.microsoft.com/en-us/products/service-bus) + +The configuration for each provider is different. Below are examples for each provider. +#### 9.1. GCP Pub/Sub + +```json +{ + "pubsub": [ + { + "type": "gcp_pubsub", + "project_id": "my-gcp-project", + "topics": { + "user-events": { + "name": "user-events-topic", + "project_id": "my-gcp-project", + "subscriptions": { + "user-notification": { + "name": "user-notification-subscription", + "push_config": { + "id": "user-push", + "service_account": "service-account@my-gcp-project.iam.gserviceaccount.com" + } + } + } + } + } + } + ] +} +``` + +#### 9.2. AWS SNS/SQS + +```json +{ + "pubsub": [ + { + "type": "aws_sns_sqs", + "topics": { + "user-notifications": { + "arn": "arn:aws:sns:us-east-1:123456789012:user-notifications", + "subscriptions": { + "user-queue": { + "arn": "arn:aws:sqs:us-east-1:123456789012:user-queue" + } + } + } + } + } + ] +} +``` + +#### 9.3. NSQ Configuration + +```json +{ + "pubsub": [ + { + "type": "nsq", + "hosts": "nsq.myencoreapp.com:4150", + "topics": { + "order-events": { + "name": "order-events-topic", + "subscriptions": { + "order-processor": { + "name": "order-processor-subscription" + } + } + } + } + } + ] +} +``` + +This guide covers typical infrastructure configurations. Adjust according to your specific requirements to optimize your Encore app's infrastructure setup. \ No newline at end of file diff --git a/docs/selfhosting/deploy-to-digital-ocean.md b/docs/selfhosting/deploy-to-digital-ocean.md new file mode 100644 index 0000000000..48034d4237 --- /dev/null +++ b/docs/selfhosting/deploy-to-digital-ocean.md @@ -0,0 +1,196 @@ +--- +seotitle: How to deploy an Encore app to DigitalOcean +seodesc: Learn how to deploy an Encore application to DigitalOcean's App Platform using Docker. +title: Deploy to DigitalOcean +--- + +If you prefer manual deployment over the automation offered by Encore's Platform, Encore simplifies the process of deploying your app to the cloud provider of your choice. This guide will walk you through deploying an Encore app to DigitalOcean's App Platform using Docker. + +### Prerequisites +1. **DigitalOcean Account**: Make sure you have a DigitalOcean account. If not, you can [sign up here](https://www.digitalocean.com/). +2. **Docker Installed**: Ensure Docker is installed on your local machine. You can download it from the [Docker website](https://www.docker.com/get-started). +3. **Encore CLI**: Install the Encore CLI if you haven’t already. You can follow the installation instructions from the [Encore documentation](https://encore.dev/docs/install). +4. **DigitalOcean CLI (Optional)**: You can install the DigitalOcean CLI for more flexibility and automation, but it’s not necessary for this tutorial. + +### Step 1: Create an Encore App +1. **Create a New Encore App**: + - If you haven’t already, create a new Encore app using the Encore CLI. + - You can use the following command to create a new app: + ```bash + encore app create myapp + ``` + - Select the `Hello World` template. + - Follow the prompts to create the app. + +2. **Build a Docker image**: + - Build the Encore app to generate the docker image for deployment: + ```bash + encore build docker myapp + ``` +### Step 2: Push the Docker Image to a Container Registry +To deploy your Docker image to DigitalOcean, you need to push it to a container registry. DigitalOcean supports +its own container registry, but you can also use DockerHub or other registries. Here’s how to push the image to DigitalOcean’s registry: + +1. **Create a DigitalOcean Container Registry**: + - Go to the [DigitalOcean Control Panel](https://cloud.digitalocean.com/registries) and create a new container registry. + - Follow the instructions to set it up. + +2. **Login to DigitalOcean's registry**: + Use the login command provided by DigitalOcean, which will look something like this: + ```bash + doctl registry login + ``` + You’ll need the DigitalOcean CLI for this, which can be installed from [DigitalOcean CLI documentation](https://docs.digitalocean.com/reference/doctl/how-to/install/). + +3. **Tag your Docker image**: + Tag your image to match the registry’s URL. + ```bash + docker tag myapp registry.digitalocean.com/YOUR_REGISTRY_NAME/myapp:latest + ``` + +4. **Push your Docker image to the registry**: + ```bash + docker push registry.digitalocean.com/YOUR_REGISTRY_NAME/myapp:latest + ``` + +### Step 3: Deploy the Docker Image to DigitalOcean App Platform +1. **Navigate to the App Platform**: + Go to [DigitalOcean's App Platform](https://cloud.digitalocean.com/apps). + +2. **Create a New App**: + - Click on **"Create App"**. + - Choose the **"DigitalOcean Container Registry"** option. + +3. **Select the Docker Image Source**: + - Select the image you pushed earlier. + +4. **Configure the App Settings**: + - **Set up scaling options**: Configure the number of containers, CPU, and memory settings. + - **Environment variables**: Add any environment variables your application might need. + - **Choose the region**: Pick a region close to your users for better performance. + +5. **Deploy the App**: + - Click **"Next"**, review the settings, and click **"Create Resources"**. + - DigitalOcean will take care of provisioning the infrastructure, pulling the Docker image, and starting the application. + +### Step 4: Monitor and Manage the App +1. **Access the Application**: + - Once deployed, you will get a public URL to access your application. + - Test the app to ensure it’s running as expected, e.g. + ```bash + curl https://myapp.ondigitalocean.app/hello/world + ``` + +2. **View Logs and Metrics**: + - Go to the **"Runtime Logs"** tab in the App Platform to view logs + - Go to the **"Insights"** tab to view performance metrics. + +3. **Manage Scaling and Deployment Settings**: + - You can change the app configuration, such as scaling settings, deployment region, or environment variables. + +### Step 5: Add a Database to Your App + +DigitalOcean’s App Platform provides managed databases, allowing you to add a database to your app easily. Here’s how to set up a managed database for your app: + +1. **Navigate to the DigitalOcean Control Panel**: + - Go to [DigitalOcean Control Panel](https://cloud.digitalocean.com/). + - Click on **"Databases"** in the left-hand sidebar. + +2. **Create a New Database Cluster**: + - Click **"Create Database Cluster"**. + - Choose **PostgreSQL** + - Select the **database version**, **data center region**, and **cluster configuration** (e.g., development or production settings based on your needs). + - **Name the database** and configure other settings if necessary, then click **"Create Database Cluster"**. + +3. **Configure the Database Settings**: + - Once the database is created, go to the **"Connection Details"** tab of the database dashboard. + - Copy the **connection string** or individual settings (host, port, username, password, database name). You will need these details to connect your app to the database. + - Download the **CA certificate** + +4. **Create a Database** + - Connect to the database using the connection string provided by DigitalOcean. + ```bash + psql -h mydb.db.ondigitalocean.com -U doadmin -d mydb -p 25060 + ``` + - Create a database + ```sql + CREATE DATABASE mydb; + ``` + - Create a table + ```sql + CREATE TABLE users ( + id SERIAL PRIMARY KEY, + name VARCHAR(50) + ); + INSERT INTO users (name) VALUES ('Alice'); + ``` + +5. **Declare a Database in your Encore app**: + - Open your Encore app’s codebase. + - Add `mydb` database to your app ([Encore Database Documentation](https://encore.dev/docs/ts/primitives/databases)) + ```typescript + const mydb = new SQLDatabase("mydb", { + migrations: "./migrations", + }); + + export const getUser = api( + { expose: true, method: "GET", path: "/names/:id" }, + async ({id}:{id:number}): Promise<{ id: number; name: string }> => { + return await mydb.queryRow`SELECT * FROM users WHERE id = ${id}` as { id: number; name: string }; + } + ); + ``` + +6. **Create an Encore Infrastructure config** + - Create a file named `infra.config.json` in the root of your Encore app. + - Add the **CA certificate** and the connection details to the file: + ```json + { + "$schema": "https://encore.dev/schemas/infra.schema.json", + "sql_servers": [ + { + "host": "mydb.db.ondigitalocean.com:25060", + "tls_config": { + "ca": "-----BEGIN CERTIFICATE-----\n..." + }, + "databases": { + "mydb": { + "username": "doadmin", + "password": {"$env": "DB_PASSWORD"} + } + } + }] + } + ``` + +7. **Set Up Environment Variables (Optional)**: + - Go to the DigitalOcean App Platform dashboard. + - Select your app. + - In the **"Settings"** section, go to **"App-Level Environment Variables"** + - Add the database password as an encrypted environment variable called `DB_PASSWORD`. + +8. **Build and push the Docker image**: + - Build the Docker image with the updated configuration. + ```bash + encore build docker --config infra.config.json myapp + ``` + - Tag and push the Docker image to the DigitalOcean container registry. + ```bash + docker tag myapp registry.digitalocean.com/YOUR_REGISTRY_NAME/myapp:latest + docker push registry.digitalocean.com/YOUR_REGISTRY_NAME/myapp:latest + ``` + +9. **Test the Database Connection**: + - Redeploy the app on DigitalOcean to apply the changes. + - Test the database connection by calling the API + ```bash + curl https://myapp.ondigitalocean.app/names/1 + ``` + +### Troubleshooting Tips +- **Deployment Failures**: Check the build logs for any errors. Make sure the Docker image is correctly tagged and pushed to the registry. +- **App Not Accessible**: Verify that the correct port is exposed in the Dockerfile and the App Platform configuration. +- **Database Connection Issues**: Ensure the database connection details are correct and the database is accessible from the app. + +### Conclusion +That’s it! You’ve successfully deployed an Encore app to DigitalOcean’s App Platform using Docker. You can now scale your app, monitor its performance, and manage it easily through the DigitalOcean dashboard. If you encounter any issues, refer to the DigitalOcean documentation or the Encore community for help. Happy coding! \ No newline at end of file