”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何使用 Docker 和 Encore 将后端应用程序部署到 DigitalOcean

如何使用 Docker 和 Encore 将后端应用程序部署到 DigitalOcean

发布于2024-11-07
浏览:871

How to deploy a backend application to DigitalOcean using Docker and Encore

? This guide shows you how to deploy an Encore application to DigitalOcean using the new encore build command, part of Encore's open source CLI.

This is handy if you prefer manual deployment over the automation offered by Encore's Cloud Platform.

Even when deploying manually, Encore simplifies the process by providing tools to build and configure your app.⚡️

Now let's take a look at how to deploy an Encore app to DigitalOcean's App Platform using Docker and encore build.?

Prerequisites

  • DigitalOcean Account: Make sure you have a DigitalOcean account. If not, you can sign up here.
  • Docker Installed: Ensure Docker is installed on your local machine. You can download it from the Docker website.
  • Encore CLI: Install the Encore CLI:
    • macOS: brew install encoredev/tap/encore
    • Linux: curl -L https://encore.dev/install.sh | bash
    • Windows: iwr https://encore.dev/install.ps1 | iex
  • 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

  • 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:
    encore app create myapp
    
    • Select the Hello World template.
    • Follow the prompts to create the app.
  • Build a Docker image:

    • Build the Encore app to generate the docker image for deployment:
    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:

  • Create a DigitalOcean Container Registry:

    • Go to the DigitalOcean Control Panel and create a new container registry.
    • Follow the instructions to set it up.
  • Login to DigitalOcean's registry:

    Use the login command provided by DigitalOcean, which will look something like this:

   doctl registry login

You’ll need the DigitalOcean CLI for this, which can be installed from DigitalOcean CLI documentation.

  • Tag your Docker image: Tag your image to match the registry’s URL.
   docker tag myapp registry.digitalocean.com/YOUR_REGISTRY_NAME/myapp:latest
  • Push your Docker image to the registry:
   docker push registry.digitalocean.com/YOUR_REGISTRY_NAME/myapp:latest

Step 3: Deploy the Docker Image to DigitalOcean App Platform

  • Navigate to the App Platform:
    Go to DigitalOcean's App Platform.

  • Create a New App:

    • Click on "Create App".
    • Choose the "DigitalOcean Container Registry" option.
  • Select the Docker Image Source:

    • Select the image you pushed earlier.
  • 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.
  • 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

  • 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.
curl https://myapp.ondigitalocean.app/hello/world
  • 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.
  • 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:

  • Navigate to the DigitalOcean Control Panel:

    • Go to DigitalOcean Control Panel.
    • Click on "Databases" in the left-hand sidebar.
  • 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".
  • 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
  • Create a Database

    • Connect to the database using the connection string provided by DigitalOcean.
   psql -h mydb.db.ondigitalocean.com -U doadmin -d mydb -p 25060
  • Create a database
    CREATE DATABASE mydb;
    ```


   - Create a table


   ```sql
     CREATE TABLE users (
        id SERIAL PRIMARY KEY,
        name VARCHAR(50)
     );
     INSERT INTO users (name) VALUES ('Alice');
  • Declare a Database in your Encore app:
    • Open your Encore app’s codebase.
    • Add mydb database to your app (Encore Database Documentation)
      const mydb = new SQLDatabase("mydb", {
         migrations: "./migrations",
      });

      export const getUser = api(
        { expose: true, method: "GET", path: "/names/:id" },
        async ({id}: {id:number}): Promise => {
          return await mydb.queryRow`SELECT * FROM users WHERE id = ${id}` as { id: number; name: string };
        }
      );
  • 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:
   {
      "$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"}
             }
         }
      }]   
   }
  • 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.
  • Build and push the Docker image:

    • Build the Docker image with the updated configuration.
   encore build docker --config infra.config.json myapp
  • Tag and push the Docker image to the DigitalOcean container registry.
   docker tag myapp registry.digitalocean.com/YOUR_REGISTRY_NAME/myapp:latest
   docker push registry.digitalocean.com/YOUR_REGISTRY_NAME/myapp:latest
  • Test the Database Connection:
    • Redeploy the app on DigitalOcean to apply the changes.
    • Test the database connection by calling the API
    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.

? Try it yourself

  • Learn about building apps using Encore with these Tutorials.?
  • Find inspiration on what to build with these Open Source App Templates.?

Wrapping up

  • ⭐️ Support the project by starring Encore on GitHub.
  • ? If you have questions or want to share your work, join the developers hangout in Encore's community on Discord.
版本声明 本文转载于:https://dev.to/encore/how-to-deploy-a-backend-application-to-digitalocean-using-docker-and-encore-1eh0?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    可以在纯CS中将多个粘性元素彼此堆叠在一起吗?
    [2这里: https://webthemez.com/demo/sticky-multi-header-scroll/index.html </main> <section> { display:grid; grid-template-...
    编程 发布于2025-07-02
  • JavaScript计算两个日期之间天数的方法
    JavaScript计算两个日期之间天数的方法
    How to Calculate the Difference Between Dates in JavascriptAs you attempt to determine the difference between two dates in Javascript, consider this s...
    编程 发布于2025-07-02
  • eval()vs. ast.literal_eval():对于用户输入,哪个Python函数更安全?
    eval()vs. ast.literal_eval():对于用户输入,哪个Python函数更安全?
    称量()和ast.literal_eval()中的Python Security 在使用用户输入时,必须优先确保安全性。强大的Python功能Eval()通常是作为潜在解决方案而出现的,但担心其潜在风险。 This article delves into the differences betwee...
    编程 发布于2025-07-02
  • Spark DataFrame添加常量列的妙招
    Spark DataFrame添加常量列的妙招
    在Spark Dataframe ,将常数列添加到Spark DataFrame,该列具有适用于所有行的任意值的Spark DataFrame,可以通过多种方式实现。使用文字值(SPARK 1.3)在尝试提供直接值时,用于此问题时,旨在为此目的的column方法可能会导致错误。 df.withCo...
    编程 发布于2025-07-02
  • PHP与C++函数重载处理的区别
    PHP与C++函数重载处理的区别
    作为经验丰富的C开发人员脱离谜题,您可能会遇到功能超载的概念。这个概念虽然在C中普遍,但在PHP中构成了独特的挑战。让我们深入研究PHP功能过载的复杂性,并探索其提供的可能性。在PHP中理解php的方法在PHP中,函数超载的概念(如C等语言)不存在。函数签名仅由其名称定义,而与他们的参数列表无关。...
    编程 发布于2025-07-02
  • 如何从Google API中检索最新的jQuery库?
    如何从Google API中检索最新的jQuery库?
    从Google APIS 问题中提供的jQuery URL是版本1.2.6。对于检索最新版本,以前有一种使用特定版本编号的替代方法,它是使用以下语法:获取最新版本:未压缩)While these legacy URLs still remain in use, it is recommended ...
    编程 发布于2025-07-02
  • MySQL中如何高效地根据两个条件INSERT或UPDATE行?
    MySQL中如何高效地根据两个条件INSERT或UPDATE行?
    在两个条件下插入或更新或更新 solution:的答案在于mysql的插入中...在重复键更新语法上。如果不存在匹配行或更新现有行,则此功能强大的功能可以通过插入新行来进行有效的数据操作。如果违反了唯一的密钥约束。实现所需的行为,该表必须具有唯一的键定义(在这种情况下为'名称'...
    编程 发布于2025-07-02
  • 如何使用PHP将斑点(图像)正确插入MySQL?
    如何使用PHP将斑点(图像)正确插入MySQL?
    essue VALUES('$this->image_id','file_get_contents($tmp_image)')";This code builds a string in PHP, but the function call ...
    编程 发布于2025-07-02
  • Java中如何使用观察者模式实现自定义事件?
    Java中如何使用观察者模式实现自定义事件?
    在Java 中创建自定义事件的自定义事件在许多编程场景中都是无关紧要的,使组件能够基于特定的触发器相互通信。本文旨在解决以下内容:问题语句我们如何在Java中实现自定义事件以促进基于特定事件的对象之间的交互,定义了管理订阅者的类界面。以下代码片段演示了如何使用观察者模式创建自定义事件: args)...
    编程 发布于2025-07-02
  • 在GO中构造SQL查询时,如何安全地加入文本和值?
    在GO中构造SQL查询时,如何安全地加入文本和值?
    在go中构造文本sql查询时,在go sql queries 中,在使用conting and contement和contement consem per时,尤其是在使用integer per当per当per时,per per per当per. [&​​&&&&&&&&&&&&&&&默元组方法在...
    编程 发布于2025-07-02
  • 如何使用Python理解有效地创建字典?
    如何使用Python理解有效地创建字典?
    在python中,词典综合提供了一种生成新词典的简洁方法。尽管它们与列表综合相似,但存在一些显着差异。与问题所暗示的不同,您无法为钥匙创建字典理解。您必须明确指定键和值。 For example:d = {n: n**2 for n in range(5)}This creates a dicti...
    编程 发布于2025-07-02
  • 如何实时捕获和流媒体以进行聊天机器人命令执行?
    如何实时捕获和流媒体以进行聊天机器人命令执行?
    在开发能够执行命令的chatbots的领域中,实时从命令执行实时捕获Stdout,一个常见的需求是能够检索和显示标准输出(stdout)在cath cath cant cant cant cant cant cant cant cant interfaces in Chate cant inter...
    编程 发布于2025-07-02
  • 如何从Python中的字符串中删除表情符号:固定常见错误的初学者指南?
    如何从Python中的字符串中删除表情符号:固定常见错误的初学者指南?
    从python import codecs import codecs import codecs 导入 text = codecs.decode('这狗\ u0001f602'.encode('utf-8'),'utf-8') 印刷(文字)#带有...
    编程 发布于2025-07-02
  • 为什么PHP的DateTime :: Modify('+1个月')会产生意外的结果?
    为什么PHP的DateTime :: Modify('+1个月')会产生意外的结果?
    使用php dateTime修改月份:发现预期的行为在使用PHP的DateTime类时,添加或减去几个月可能并不总是会产生预期的结果。正如文档所警告的那样,“当心”这些操作的“不像看起来那样直观。 考虑文档中给出的示例:这是内部发生的事情: 现在在3月3日添加另一个月,因为2月在2001年只有2...
    编程 发布于2025-07-02
  • Java中假唤醒真的会发生吗?
    Java中假唤醒真的会发生吗?
    在Java中的浪费唤醒:真实性或神话?在Java同步中伪装唤醒的概念已经是讨论的主题。尽管存在这种行为的潜力,但问题仍然存在:它们实际上是在实践中发生的吗? Linux的唤醒机制根据Wikipedia关于伪造唤醒的文章,linux实现了pthread_cond_wait()功能的Linux实现,利用...
    编程 发布于2025-07-02

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3