在 Ubuntu 20.04 上使用 Golang 和 MongoDB 创建 CRUD 应用程序

1.介绍

MongoDB是最好的基于文档的开源数据库管理系统之一。由于其灵活的设计模式,您可以在各种业务系统中使用该应用程序,这是传统 SQL 数据库无法满足的。

凭借其强大的数据库模式,MongoDB平台适用于设置用于管理产品数据,创建内容管理系统(CMS)的系统,以及在大多数情况下存储和查询大数据的系统。

另一方面,Golang 是一种快速、可扩展且易于学习的现代编程语言,用于编码高级软件应用程序。由于MongoDB为Golang语言提供了全面的API,因此您可以将这两个应用程序一起使用,为金融,电子商务,研究等提供解决方案。

在本指南中,您将使用 MongoDB 设置一个数据库,并从自定义 Golang 应用程序与其通信,以在 Ubuntu 20.04 服务器上执行基本的创建、读取、更新和删除 (CRUD) 操作。

2.准备工作

要继续执行本指南,请确保您已获得以下各项:

  • Ubuntu 20.04 服务器。
  • 具有 sudo 权限的非 root 用户。
  • 使用用户帐户和密码配置的 MongoDB 数据库。
  • 一个戈朗包。

3. 创建 MongoDB 数据库

数据驱动应用程序必须能够存储、检索、更新和删除记录。只有在为软件设置数据库后,才能执行所有这些操作。通过 SSH 连接到您的服务器,然后按照以下步骤初始化 MongoDB 数据库。

  1. 登录到您的MongoDB数据库。替换为数据库的管理员帐户。mongo_db_admin
    $ mongosh -u mongo_db_admin -p --authenticationDatabase admin
  2. 出现提示时,输入MongoDB帐户的密码,然后按继续。接下来,运行下面的语句以创建数据库。ENTERshop_db
    test> use shop_db
  3. 确认已切换到新数据库。shop_db
    switched to db shop_db
  4. 接下来,使用 MongoDB 函数在新集合中插入三个文档。productsinsertMany()
    shop_db> db.products.insertMany([
    
                {"product_id" : 1,
    
                 "product_name" : "LEATHER BELT",
    
                 "retail_price" : 24.35   
    
                },
    
                {"product_id" : 2,
    
                 "product_name" : "WINTER JACKET",
    
                 "retail_price" : 99.95    
    
                },
    
                {"product_id" : 3,
    
                 "product_name" : "WOOLEN SWEATER",
    
                 "retail_price" : 43.20
    
                }  
    
               ]);
  5. 通过确认下面的输出来确保命令已成功。
    {
    
      acknowledged: true,
    
      insertedIds: {
    
        '0': ObjectId("62188b2358979df39bbcf178"),
    
        '1': ObjectId("62188b2358979df39bbcf179"),
    
        '2': ObjectId("62188b2358979df39bbcf17a")
    
      }
    
    }
  6. 接下来,使用以下语句查询集合以确保数据已到位。products
    shop_db> db.products.find()
  7. 您应该获得所有产品的列表以及相关的产品,如下所示。_ids
    [
    
      {
    
        _id: ObjectId("62188b2358979df39bbcf178"),
    
        product_id: 1,
    
        product_name: 'LEATHER BELT',
    
        retail_price: 24.35
    
      },
    
      {
    
        _id: ObjectId("62188b2358979df39bbcf179"),
    
        product_id: 2,
    
        product_name: 'WINTER JACKET',
    
        retail_price: 99.95
    
      },
    
      {
    
        _id: ObjectId("62188b2358979df39bbcf17a"),
    
        product_id: 3,
    
        product_name: 'WOOLEN SWEATER',
    
        retail_price: 43.2
    
      }
    
    ]
  8. 从 MongoDB 服务器注销。
    shop_db> quit
  9. 现在,您已经设置了数据库集合和示例文档。在接下来的步骤中,您将使用 Golang 语言创建一些脚本来操作您的 MongoDB 集合。shop_dbproducts

4. 创建文件main.go

该文件将保存应用程序的函数。这是执行应用程序时触发的主要方法。main.gomain()

  1. 在创建文件的源代码之前,请创建一个目录以将源代码与其余 Linux 文件分开。main.goproject
    $ mkdir project
  2. 然后,切换到新目录。project
    $ cd project
  3. 接下来,使用文本编辑器打开一个新文件以进行编辑。nanomain.go
    $ nano main.go
  4. 打开文件后,在文件中输入以下信息。将 替换为 MongoDB 用户帐户的正确值。main.gomongo_db_adminEXAMPLE_PASSWORD
    package main
    
    
    
    import (
    
        "context"
    
        "net/http"
    
        "encoding/json" 
    
        _"log" 
    
        "fmt" 
    
        "go.mongodb.org/mongo-driver/mongo" 
    
    "go.mongodb.org/mongo-driver/mongo/options"         
    
    )
    
    
    
    const (  
    
        dbUser = "mongo_db_admin"
    
        dbPass = "EXAMPLE_PASSWORD"
    
        dbName = "shop_db"
    
    )
    
    
    
    func main() {
    
         http.HandleFunc("/api/v1/products", requestHandler)
    
         http.ListenAndServe(":8080", nil)
    
    }
    
    
    
    func requestHandler(w http.ResponseWriter, req *http.Request) {
    
    
    
        w.Header().Set("Content-Type", "application/json")
    
    
    
        response := map[string]interface{}{}
    
    
    
        ctx := context.Background()
    
    
    
        client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://" + dbUser + ":" + dbPass + "@localhost:27017"))
    
    
    
        if err != nil { 
    
            fmt.Println(err.Error())
    
        } 
    
    
    
        collection := client.Database(dbName).Collection("products")  
    
    
    
        data := map[string]interface{}{} 
    
    
    
        err = json.NewDecoder(req.Body).Decode(&data)
    
    
    
        if err != nil { 
    
            fmt.Println(err.Error())
    
        }
    
    
    
        switch req.Method {
    
            case "POST":
    
                response, err = createRecord(collection, ctx, data)
    
            case "GET":
    
                response, err = getRecords(collection, ctx)
    
            case "PUT":
    
                response, err = updateRecord(collection, ctx, data)
    
            case "DELETE":
    
                response, err = deleteRecord(collection, ctx, data)
    
        }
    
    
    
        if err != nil { 
    
            response = map[string]interface{}{"error": err.Error(),}  
    
        } 
    
    
    
        enc := json.NewEncoder(w)
    
        enc.SetIndent("", "  ")
    
    
    
        if err := enc.Encode(response); err != nil {
    
            fmt.Println(err.Error())
    
        }   
    
    }
  5. 完成编辑后保存并关闭文件。
  6. 在上面的文件中,您将创建一个 Web 服务器,该服务器使用语句和 .8080http.HandleFunc("/api/v1/products", requestHandler)http.ListenAndServe(":8080", nil)
  7. 在该函数下,您将连接到之前创建的 MongoDB 实例。接下来,使用 Golang 语句通过传递集合引用将 HTTP 请求路由到相应的 CRUD 函数。最后,您将使用 JSON 函数以人类可读的格式格式化和输出数据。requestHandler()switchproducts
  8. 创建文件后,现在将在不同的文件上设置单独的函数,以处理应用程序的所有 CRUD 操作。main.go

5. 设置新文件create_record.go

要为 CRUD 操作设置的第一个文件是该文件。此文件包含用于将文档插入集合的功能。create_record.goproducts

  1. 运行以下命令以设置文件。create_record.go
    $ nano create_record.go
  2. 接下来,在文件中输入以下信息。
    package main
    
    
    
    import (
    
        "context"      
    
        "go.mongodb.org/mongo-driver/mongo"       
    
    )
    
    
    
    func createRecord(collection *mongo.Collection, ctx context.Context, data map[string]interface{})(map[string]interface{}, error){     
    
    
    
        req, err := collection.InsertOne(ctx, data)
    
    
    
        if err != nil { 
    
            return nil, err                    
    
        }
    
    
    
        insertedId := req.InsertedID
    
    
    
        res := map[string]interface{}{
    
                   "data" : map[string]interface{}{                            
    
                        "insertedId": insertedId,
    
                    },
    
               } 
    
    
    
        return res, nil
    
    }
  3. 保存并关闭文件。
  4. 上面文件中的主要功能是将BSON有效负载从请求HTTP客户端保存到MongoDB数据库。在上述文件下,如果语句执行没有任何错误,则返回新文档的 。collection.InsertOne(ctx, data)insertedId
  5. 接下来,您将设置一个函数来从 MongoDB 集合中删除文档。

6. 创建文件delete_record.go

与任何其他应用程序一样,如果不再需要记录,则必须提供从集合中删除记录的功能。products

  1. 使用 打开一个新文件 。delete_record.gonano
    $ nano delete_record.go
  2. 接下来,在文件中输入以下信息。delete_record.go
    package main
    
    
    
    import (
    
        "context"          
    
        "go.mongodb.org/mongo-driver/mongo"     
    
        "go.mongodb.org/mongo-driver/bson"
    
    )
    
    
    
    func deleteRecord(collection *mongo.Collection, ctx context.Context, data map[string]interface{})(map[string]interface{}, error){
    
    
    
        _, err := collection.DeleteOne(ctx, bson.M{"product_id": data["product_id"]})
    
    
    
        if err != nil { 
    
            return nil, err                    
    
        }     
    
    
    
        res := map[string]interface{}{
    
                   "data" : "Document deleted successfully.",   
    
               } 
    
    
    
        return res, nil
    
    }
  3. 保存并关闭文件。
  4. 在上面的文件中,您正在使用该函数从MongoDB数据库中删除文档。为了确保删除正确的文档,请使用语句检索要删除的项目。换句话说,在向应用程序提交请求时,您应该在 HTTP 有效负载中传递 a。collection.DeleteOne(...)product_idbson.M{"product_id": data["product_id"]}product_idDELETE
  5. 接下来,您将设置一个函数来更新文档。

7. 创建一个新文件update_record.go

您将使用该文件对文档进行更改。此文件下的 function() 依赖于包含要更新的字段的有效负载以及文档的唯一性。update_record.goupdateRecord()product_id

  1. 用于打开新文件。nanoupdate_record.go
    $ nano update_record.go
  2. 接下来,在文件中输入以下信息。update_record.go
    package main
    
    
    
    import (
    
        "context"
    
        "go.mongodb.org/mongo-driver/bson"     
    
        "go.mongodb.org/mongo-driver/mongo" 
    
    )
    
    
    
    func updateRecord(collection *mongo.Collection, ctx context.Context, data map[string]interface{})(map[string]interface{}, error){            
    
    
    
        filter := bson.M{"product_id": data["product_id"]}
    
        fields := bson.M{"$set": data}
    
    
    
        _, err := collection.UpdateOne(ctx, filter, fields)
    
    
    
        if err != nil { 
    
            return nil, err                    
    
        }
    
    
    
        res := map[string]interface{}{
    
                   "data" : "Document updated successfully.",   
    
               } 
    
    
    
        return res, nil
    
    }
  3. 在上面的文件中,您首先使用语句为要更新的文档提供一个参数。然后,您将使用语句提交新的文档值。此处的值来自请求客户端提交的 HTTP 有效负载。filterfilter := bson.M{"product_id": data["product_id"]}fields := bson.M{"$set": data}data
  4. 接下来,使用该函数向集合提交更新请求。在下一步中,您将创建一个函数,用于从 MongoDB 集合中检索记录。collection.UpdateOne(ctx, filter, fields)

8. 创建一个新文件get_records.go

MongoDB API for Golang具有非常直观的功能,用于以地图的形式从数据库中检索文档。您将使用这些函数查询数据库集合并将文档返回到之前创建的文件。main.go

  1. 用于创建新文件。nanoget_records.go
    $ nano get_records.go
  2. 然后,在文件中输入以下信息。get_records.go
    package main
    
    
    
    import (
    
        "context"          
    
        "go.mongodb.org/mongo-driver/bson"
    
        "go.mongodb.org/mongo-driver/mongo" 
    
    )
    
    
    
    func getRecords(collection *mongo.Collection, ctx context.Context)(map[string]interface{}, error){ 
    
    
    
        cur, err := collection.Find(ctx, bson.D{})
    
    
    
        if err != nil { 
    
            return nil, err
    
        }
    
    
    
        defer cur.Close(ctx) 
    
    
    
        var products []bson.M           
    
    
    
        for cur.Next(ctx) {
    
    
    
            var product bson.M
    
    
    
            if err = cur.Decode(&product); err != nil {
    
                return nil, err
    
            }
    
    
    
            products = append(products, product)
    
    
    
        }
    
    
    
        res := map[string]interface{}{}
    
    
    
        res = map[string]interface{}{
    
                  "data" : products,   
    
              }             
    
    
    
        return res, nil
    
    }
  3. 保存并关闭文件。
  4. 在上面的文件中,您将使用该函数返回已保存在集合中的文档的光标。然后,您将使用循环循环访问稍后附加到数组的文档。cur, err := collection.Find(ctx, bson.D{})productsfor cur.Next(ctx) {...}products []bson.M
  5. 最后,您将数据作为映射返回到调用函数。现在,你已为应用设置了所有 CRUD 函数。在下一步中,您将测试应用程序以确保一切按预期工作。[string]interface{}

9. 测试 Golang 应用程序

在此步骤中,你将测试应用程序,以确保它可以处理所有 CRUD 操作,而不会出现任何错误。

  1. 导入 Golang 应用程序的 MongoDB 驱动程序。
    $ go get go.mongodb.org/mongo-driver/mongo
  2. 接下来,执行以下命令以运行应用程序。以下命令允许应用程序启动 Web 服务器并侦听端口上的传入 HTTP 连接,并具有阻止功能。不要在此 SSH 终端窗口上运行任何其他命令。8080
    $ go run ./
  3. 接下来,在单独的终端窗口中建立与服务器的新 SSH 会话。
  4. 尝试通过运行以下命令创建新文档。curl
    $ curl -X POST localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"product_id": 4, "product_name": "WIRELESS KEYBOARD",  "retail_price": 45.30}'
  5. 您应该获得新记录,如下所示。insertedId
    {
    
      "data": {
    
        "insertedId": "621c9acf3f4e8882c3eeabef"
    
      }
    
    }
  6. 接下来,使用以下命令从集合中检索所有文档。products
    $ curl -X GET localhost:8080/api/v1/products
  7. 现在,您应该会看到四个文档的列表。前三个是首次初始化数据库时设置的文档,最后一个 record() 是您刚刚使用该命令插入的文档。WIRELESS KEYBOARDcurl
    {
    
      "data": [
    
        {
    
          "_id": "621c9aaf35ece941bcc5b80d",
    
          "product_id": 1,
    
          "product_name": "LEATHER BELT",
    
          "retail_price": 24.35
    
        },
    
        {
    
          "_id": "621c9aaf35ece941bcc5b80e",
    
          "product_id": 2,
    
          "product_name": "WINTER JACKET",
    
          "retail_price": 99.95
    
        },
    
        {
    
          "_id": "621c9aaf35ece941bcc5b80f",
    
          "product_id": 3,
    
          "product_name": "WOOLEN SWEATER",
    
          "retail_price": 43.2
    
        },
    
        {
    
          "_id": "621c9acf3f4e8882c3eeabef",
    
          "product_id": 4,
    
          "product_name": "WIRELESS KEYBOARD",
    
          "retail_price": 45.3
    
        }
    
      ]
    
    }
  8. 接下来,运行以下命令以使用 of 更新文档并将其 from 更改为 。product_id1product_nameLEATHER BELTMETAL BUCKLE LEATHER BELT
    $ curl -X PUT localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"product_id": 1, "product_name": "METAL BUCKLE LEATHER BELT",  "retail_price": 45.30}'
  9. 以下输出确认你已成功更新产品详细信息。
    {
    
      "data": "Document updated successfully."
    
    }
  10. 通过运行以下命令删除带有 of () 的文档。product_id4WIRELESS KEYBOARD
    $ curl -X DELETE localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"product_id": 4}'
  11. 您应该会收到以下确认消息。
    {
    
      "data": "Document deleted successfully."
    
    }
  12. 接下来,再次检索记录,以确保已在集合中执行 和 操作。UPDATEDELETEproducts
    $ curl -X GET localhost:8080/api/v1/products
  13. 从下面的输出中可以看到,您已经删除了带有 of 的文档,并且您还成功地将文档的值更新为 of 到 。product_id4product_id1METAL BUCKLE LEATHER BELT
    {
    
      "data": [
    
        {
    
          "_id": "621c9aaf35ece941bcc5b80d",
    
          "product_id": 1,
    
          "product_name": "METAL BUCKLE LEATHER BELT",
    
          "retail_price": 45.3
    
        },
    
        {
    
          "_id": "621c9aaf35ece941bcc5b80e",
    
          "product_id": 2,
    
          "product_name": "WINTER JACKET",
    
          "retail_price": 99.95
    
        },
    
        {
    
          "_id": "621c9aaf35ece941bcc5b80f",
    
          "product_id": 3,
    
          "product_name": "WOOLEN SWEATER",
    
          "retail_price": 43.2
    
        }
    
      ]        
    
    }
  14. 您的代码现在按预期工作,并且能够处理所有 CRUD 操作。

10.结论

在本指南中,您使用Golang编程语言在Ubuntu 20.04服务器上连接和操作MongoDB集合中的数据。使用 Golang 设计下一个数据驱动的 MongoDB 应用程序时,请使用本指南中的函数。

如何在 Ubuntu 20.04 LTS 上安装 RethinkDB

您是否正在寻找一个易于使用且扩展良好的数据库?RethinkDB 是一个开源分布式文档存储,提供实时推送功能。

本文解释了如何在 Ubuntu 20.04 LTS 上安装 RethinkDB。

一、准备工作

  • 部署 Ubuntu 服务器实例。
  • 使用 sudo 用户登录到服务器。
  • 更新服务器。

二、添加 RethinkDB 存储库和 GPG 密钥

默认的 RethinkDB 包不包含在 Ubuntu 20.04 存储库中,因此您需要在安装 RethinkDB 之前添加它。

  1. RethinkDB团队拥有自己的Ubuntu Linux存储库。将存储库添加到 .APT
    $ source /etc/lsb-release && echo "deb https://download.rethinkdb.com/repository/ubuntu-$DISTRIB_CODENAME $DISTRIB_CODENAME main" | sudo tee /etc/apt/sources.list.d/rethinkdb.list
  2. 该软件包使用 RethinkDB 团队的 GPG 密钥进行签名,因此应添加 GPG 密钥以避免任何警告。通过运行以下命令添加 GPG 密钥。
    $ wget -qO- https://download.rethinkdb.com/repository/raw/pubkey.gpg | sudo apt-key add -
    
    OK
  3. 添加存储库和密钥后,通过运行以下命令进行更新。APT
    sudo apt update -y

 三、在 Ubuntu 20.04 上安装 RethinkDB

添加存储库和密钥后,运行以下命令在 Ubuntu 20.04 上安装 RethinkDB。

    sudo apt install rethinkdb -y

安装过程应该需要一些时间才能完成。安装后,使用以下命令启动 RethinkDB 并使其在启动时自动启动。

    sudo systemctl start rethinkdb 

    sudo systemctl enable rethinkdb

 四、访问 RethinkDB Web 界面

此时,RethinkDB 应该运行在您的 Ubuntu 20.04 服务器上。RethinkDB 还提供了一个 Web 界面来管理您的集群,您可以使用浏览器访问该界面。现在将您的浏览器指向 localhost,并在 URL 末尾添加:8080。

    http://localhost:8080

您的 RethinkDB Web 界面应该会显示出来。

五、结论

现在,您在 Ubuntu 20.04 服务器上有一个 RethinkDB 的工作实例,可用于您的应用程序。

如何在 Ubuntu 20.04 上安装 Supabase

一、介绍

在本教程中,您将学习如何在 Ubuntu 20.04 上安装和配置 Supabase。您还将学习如何使用安全密钥和反向代理保护您的 Supabase 实例。

Supabase 是 Firebase 的替代方案,通过 Web 界面提供 PostgreSQL 数据库,用户身份验证,存储和实时 API。Supabase 还具有开源 API 库,可以与其他应用程序轻松交互。

二、准备工作

在开始之前,您应该:

  • 部署至少具有 2 GB RAM 的 Ubuntu 20.04 服务器。
  • 创建具有 sudo 权限的非 root 用户。
  • 以非 root 用户身份登录到您的服务器。
  • 确保服务器已完全更新。
  • 在 Vultr 防火墙或 ufw 上打开端口 433(如果适用)。

您还需要一个指向您的服务器的域名。这是因为SSL证书生成器Certbot/Let’s Encrypt)不提供IP地址的SSL证书。您需要创建一个指向您的服务器的域名。也可以改用 HTTP,但不建议这样做。

三、安装

3.1、Nginx、Certbot 和 Git

  1. 安装 Nginx 和 Git。
    $ sudo apt install nginx git
  2. 卸载任何旧版本的 Certbot 和 Docker。
    $ sudo apt remove certbot docker docker.io containerd runc
  3. 更新快照安装程序。
    $ sudo snap install core; sudo snap refresh core
  4. 使用 安装 Certbot。snap
    $ sudo snap install --classic certbot
  5. 运行 Certbot 并按照提示输入您的域名并将所有流量重定向到 HTTPS。
    $ sudo certbot certonly --standalone
  6. 记下提供的证书和私钥路径。根据所使用的域,它会有所不同。
    Certificate Path: /etc/letsencrypt/live/example.com/fullchain.pem
    
    Private Key Path: /etc/letsencrypt/live/example.com/privkey.pem

如果您使用了其他 SSL 提供程序,请确保证书和私钥文件存储在系统上的某个位置,并且您知道它们的完整文件路径。

3.2、Docker

  1. 使用 安装 Docker 。snap
    $ sudo snap install docker
  2. 克隆 Supabase 存储库。
    $ git clone --depth 1 https://github.com/supabase/supabase.git
  3. 打开文件夹。docker
    $ cd supabase/docker
  4. 将文件复制到 。.env.example.env
    $ cp .env.example .env
  5. 在文本编辑器中打开文件。.env
    $ nano .env
  6. 在浏览器中打开一个强密码生成器,如Bitwarden,并生成一个新密码。它应包含超过 25 个字符。
    https://bitwarden.com/password-generator/
  7. 将文件中的值替换为生成的密码。POSTGRES_PASSWORD.env
    POSTGRES_PASSWORD=<password>
  8. 生成另一个密码,其中包含超过 32 个字符且没有特殊字符。将文件中的值替换为新生成的密码。JWT_SECRET.env
    JWT_SECRET=<new password>
  9. 使用您的在Supabase网站上生成一个。复制并粘贴您的 ,将“预配置有效负载”类型切换为 ,按“生成 JWT”,然后将“生成的令牌”结果复制到文件中的值中。JWT_SECRETANON_KEYJWT_SECRETANON_KEYANON_KEY.env
    https://supabase.com/docs/guides/hosting/overview#api-keys
    
    
    
    ANON_KEY=<generated key>
  10. 在使用相同的 .将其粘贴为文件中的值。SERVICE_KEYJWT_SECRETSERVICE_ROLE_KEY.env
    SERVICE_ROLE_KEY=<generated key>
  11. 关闭文本编辑器并保存更改,方法是使用 + ,然后使用 ,后跟 。CTRLXYENTER
  12. 导航到该文件夹并在文本编辑器中打开。volumes/apikong.yml
    $ cd volumes/api
    
    $ nano kong.yml
  13. 在 下,将用户的替换为文件中的值。consumersanonkeyANON_KEY.env
    consumers:
    
    - username: anon
    
      keyauth_credentials:
    
      - key: [anon key]
  14. 将用户的替换为文件中的值。service_rolekeySERVICE_ROLE_KEY.env
    consumers:
    
    - username: anon
    
      keyauth_credentials:
    
      - key: [anon key]
    
    - username: service_role
    
      keyauth_credentials:
    
      - key: [service_role key]
  15. Close your text editor again by using + , then , followed by .CTRLXYENTER
  16. Run Supabase by using in detached mode. This may take 10-15 minutes.docker-compose
    $ sudo docker-compose up -d
  17. Check that Supabase is running by using . The status should be .dockerUp
    $ sudo docker ps
    
    
    
    STATUS
    
    Up x seconds/minutes

您现在已成功安装 Supabase 并获得签名的 SSL 证书。

四、使用 Nginx 反向代理保护 Supabase

您现在可以使用SSL证书和Nginx来保护Supabase安装。确保替换为您选择的域名或 IP 地址。example.com

  1. 删除 Nginx 默认配置文件。
    $ sudo rm /etc/nginx/sites-enabled/default
  2. 在文本编辑器的 Nginx 目录中创建并打开新的配置文件。sites-available
    $ sudo nano /etc/nginx/sites-available/supabase
  3. 将以下内容粘贴到文件中,并替换为您的域名或 IP 地址。确保 和 行指向您的 SSL 证书。example.comssl_certificatessl_certificate_key
    upstream supabase {
    
      server localhost:3000;
    
    }
    
    
    
    server {
    
      listen 443 ssl http2;
    
      server_name example.com;
    
    
    
      gzip on;
    
    
    
      ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    
      ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    
      ssl_session_cache builtin:1000 shared:SSL:10m; 
    
      ssl_session_cache shared:MySSL:10m;
    
      ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    
      ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    
      ssl_prefer_server_ciphers on;
    
    
    
    # REST API
    
    location ~ ^/rest/v1/(.*)$ {
    
        proxy_set_header Host $host;
    
        proxy_pass http://kong:8000;
    
        proxy_redirect off;
    
      }
    
    
    
    # Authentication
    
    location ~ ^/auth/v1/(.*)$ {
    
        proxy_set_header Host $host;
    
        proxy_pass http://kong:8000;
    
        proxy_redirect off;
    
      }
    
    
    
    # Realtime
    
    location ~ ^/realtime/v1/(.*)$ {
    
        proxy_redirect off;
    
        proxy_pass http://kong:8000;
    
        proxy_http_version 1.1;
    
        proxy_set_header Upgrade $http_upgrade;
    
        proxy_set_header Connection $connection_upgrade;
    
        proxy_set_header Host $host;
    
      }
    
    }

    此 Nginx 配置将在端口 443 上为 Supabase 提供服务,并将使用您之前生成的 SSL 证书和私钥。它还会将 和 路由指向 Kong API 服务器。/rest/v1//auth/v1//realtime/v1/

  4. 退出文本编辑器并保存更改,方法是按 + ,然后按 ,然后按 。CTRLXYENTER
  5. 在 Nginx 的目录中创建一个指向新配置文件的链接。sites-enabled
    $ sudo ln -s /etc/nginx/sites-available/supabase /etc/nginx/sites-enabled/supabase.conf
  6. 测试配置文件。如果测试成功,您将看到 和消息。syntax is oktest is successful
    $ sudo nginx -t
    
    nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
    
    nginx: configuration file /etc/nginx/nginx.conf test is successful
  7. 重新加载 Nginx 以应用您的更改。
    $ sudo /etc/init.d/nginx reload

 五、整理步骤

您现在应该导航到您的 Supabase 安装。

https://example.com

从那里,您可以配置数据库、身份验证和文件存储。

恭喜,您已成功安装 Supabase 并使用 SSL 证书和 Nginx 反向代理对其进行保护。

在 Debian 或 Ubuntu 上使用 ProFTPd 安装 FTP 服务器

一、准备工作

  • 新部署的 Vultr Debian 或 Ubuntu 服务器实例。
  • 用户。

二、安装

更新系统。

sudo apt-get update

sudo apt-get dist-upgrade

安装。proftpd

sudo apt-get install proftpd

在安装过程中,系统会询问您是否要安装 inormode。选择模式。inetdstandalonestandalone

三、配置

打开 Proftpd 配置文件。

sudo nano /etc/proftpd/proftpd.conf

该文件将类似于以下文本。

#

# /etc/proftpd/proftpd.conf -- This is a basic ProFTPD configuration file.

# To really apply changes, reload proftpd after modifications, if

# it runs in daemon mode. It is not required in inetd/xinetd mode.

#



# Includes DSO modules

Include /etc/proftpd/modules.conf



# Set off to disable IPv6 support which is annoying on IPv4 only boxes.

UseIPv6                         on

# If set on you can experience a longer connection delay in many cases.

IdentLookups                    off



ServerName                      "Debian"

ServerType                      standalone

DeferWelcome                    off



MultilineRFC2228                on

DefaultServer                   on

ShowSymlinks                    on



TimeoutNoTransfer               600

TimeoutStalled                  600

TimeoutIdle                     1200



DisplayLogin                    welcome.msg

DisplayChdir                    .message true

ListOptions                     "-l"



DenyFilter                      \*.*/



# Use this to jail all users in their homes

# DefaultRoot                     ~



# Users require a valid shell listed in /etc/shells to login.

# Use this directive to release that constrain.

RequireValidShell               off



# Port 21 is the standard FTP port.

Port                            21

...

2.2、主要配置指令

  • ServerName:指定 FTP 服务器的名称。当客户端连接到服务器时,将显示此名称。
  • TimeoutIdle:如果客户端在 FTP 服务器上不再处于活动状态,则客户端将自动断开连接的时间(以秒为单位)。
  • DefaultRoot:控制登录时分配给用户的默认根目录。
  • Port:FTP 服务器的连接端口。几乎在所有时间,此端口都存在,除非您被防火墙阻止,否则您不必更改它。21
  • PassivePorts:限制服务器从客户端发送命令时将从中选择的端口范围。PASV
  • MaxInstances:您希望在 FTP 服务器上允许的最大同时连接数。

现在,我们必须激活该选项。为此,请找到“注释”行并取消注释。DefaultRootDefaultRoot

DefaultRoot                     ~

该值意味着用户将被限制为个人文件夹(例如)。~/home/user12

注意:默认情况下,连接到 FTP 服务器的人可以访问所有服务器文件夹,因此建议启用该选项。DefaultRoot

改变的。ServerName

ServerName : the name of your FTP server

查找并取消注释以下行(删除每行开头的行),以允许匿名连接到您的服务器。#

# A basic anonymous configuration, no upload directories.



 <Anonymous ~ftp>

   User                         ftp

   Group                        nogroup

   # We want clients to be able to login with "anonymous" as well as "ftp"

   UserAlias                    anonymous ftp

   # Cosmetic changes, all files belongs to ftp user

   DirFakeUser  on ftp

   DirFakeGroup on ftp



   RequireValidShell            off



   # Limit the maximum number of anonymous logins

   MaxClients                   10



   # We want 'welcome.msg' displayed at login, and '.message' displayed

   # in each newly chdired directory.

   DisplayLogin                 welcome.msg

   DisplayFirstChdir            .message



   # Limit WRITE everywhere in the anonymous chroot

   <Directory *>

     <Limit WRITE>

       DenyAll

     </Limit>

   </Directory>

 </Anonymous>

: 如果在 FTP 服务器上启用匿名连接,则任何用户都可以连接到该服务器。他们将有权访问目录,并且能够读取和下载文件,但不能修改或添加文件。/home/ftp

您可以通过添加以下行来禁止根用户访问 FTP。

RootLogin off

更改配置后,重新启动服务器。

sudo service proftpd restart

注意:如果错误行显示为“无法解析主机”,请注意这无关紧要,您可以忽略它。

三、添加 FTP 用户

添加用户,例如“”。myuser

useradd --shell /bin/false myuser

创建用户 “” 的主目录。myuser

mkdir /home/myuser

将该目录的所有权更改为用户和组 “”。myuser

chown myuser:myuser /home/myuser/

为用户“”设置密码。myuser

passwd myuser

使用设置好的用户名和密码连接上即可。

Ubuntu 多线程下载软件

有时候因为更新源的原因,更新软件速度实在是太慢,所以需要多线程下载。

解决方法

1. 安装需要用到的软件包:

sudo apt-get install axel

2. 下载多线程脚本:

http://www.mattparnell.com/linux/apt-fast/apt-fast.sh

3. 将其移至 ~bin 目录:

sudo mv /your_dir/apt-fast.sh /usr/local/bin/apt-fast
sudo chmod +x /usr/bin/apt-fast

现在已经设置好了,默认是 4 线程同时下载,使用如下命令更新软件:

apt-fast update
apt-fast upgrade

手动修改线程数

1. 编辑 axel 的配置文件。

查找 # num_connections = 4,

vim /etc/axelrc

2. 将其后面追加:

num_connections = xx

xx 为自己需要的线程数,例如 6,太高了作用不大。