如何在Ubuntu 18.04上使用Nginx部署Go Web应用程序

The author selected the Tech Education Fund to receive a donation as part of the Write for DOnations program.

作者选择了Tech Education Fund作为“ Write for DOnations”计划的一部分来接受捐赠。

介绍 (Introduction)

Go is a general-purpose programming language that is gradually becoming one of the most popular web back-end programming languages. By focusing on simplicity, the designers of Go created a language that is both easy to learn and faster than many other languages for web applications, leveraging efficient features like its ability to handle multiple requests at a time due to its concurrency. Because of this, deploying a web application in Go will be useful to many back-end developers.

Go是一种通用编程语言,正逐渐成为最流行的Web后端编程语言之一。 通过专注于简单性,Go的设计师创造了一种语言,它比Web应用程序的许多其他语言更易于学习并且速度更快,这是因为它具有并发性,从而利用了诸如一次处理多个请求的能力之类的高效功能。 因此,在Go中部署Web应用程序对许多后端开发人员将非常有用。

Nginx is one of the most popular web servers in the world due to its lightweight resource usage and its reliability under load. Many of the largest and most highly trafficked sites on the internet depend on Nginx to serve their content. In deployment, Nginx is often used as a load balancer or a reverse proxy to increase security and make the application more robust. In conjunction with a Go web back-end, Nginx can serve up a powerful and fast web application.

Nginx由于其轻量级资源使用和负载可靠性而成为全球最受欢迎的Web服务器之一。 互联网上许多最大,流量最大的站点都依赖Nginx来提供其内容。 在部署中,Nginx通常用作负载平衡器或反向代理,以提高安全性并使应用程序更强大。 结合Go Web后端,Nginx可以提供功能强大且快速的Web应用程序。

In this tutorial, you will build a Hello World web application in Go and deploy it on an Ubuntu 18.04 server using Nginx as a reverse proxy.

在本教程中,您将在Go中构建一个Hello World Web应用程序,并使用Nginx作为反向代理将其部署在Ubuntu 18.04服务器上。

先决条件 (Prerequisites)

To follow this tutorial, you will need the following:

要遵循本教程,您将需要以下内容:

Additionally, in order to achieve a production-grade deployment of your Go web application, it’s important that you keep your server secure by installing a TLS/SSL certificate. This step is strongly encouraged. To secure your Go web application, follow How To Secure Nginx with Let’s Encrypt on Ubuntu 18.04 after Step 3 of this tutorial to obtain the free TLS/SSL certificate.

此外,为了实现Go Web应用程序的生产级部署,通过安装TLS / SSL证书来确保服务器安全非常重要。 强烈鼓励这一步骤。 要保护Go Web应用程序的安全,请在本教程的第3步之后按照如何在Ubuntu 18.04上使用Let's Encrypt来保护Nginx,以获取免费的TLS / SSL证书。

步骤1 —构建Go Web应用程序 (Step 1 — Building the Go Web Application)

In this step, you will build a sample Go web application that displays Hello World at your_domain and greets the user at your_domain/greet/. If you would like to learn more about the basics of programming in Go, check out our How To Write Your First Program in Go article.

在此步骤中,您将构建一个示例Go Web应用程序,该应用程序在your_domain中显示Hello World并在your_domain /greet/向用户your_domain /greet/ 。 如果您想了解有关Go语言编程基础的更多信息,请参阅我们的如何编写Go语言中的一个程序文章。

First, create a new directory in your GOPATH directory to hold the source file. You can name the folder whatever you like, but this tutorial will use go-web:

首先,在您的GOPATH目录中创建一个新目录来保存源文件。 您可以随意命名该文件夹,但是本教程将使用go-web

  • mkdir $GOPATH/go-web

    mkdir $ GOPATH / 上网

Following the file structure suggested in the prerequisite tutorial How To Install Go and Set Up a Local Programming Environment on Ubuntu 18.04, this will give your directory the path of ~/go/go-web.

按照先决条件教程如何在Ubuntu 18.04上安装Go并设置本地编程环境中建议的文件结构,这将为您的目录提供~/go/go-web的路径。

Next, run the following to change directory to your newly created folder in your GOPATH:

接下来,运行以下命令将目录更改为您在GOPATH新创建的文件夹:

  • cd $GOPATH/go-web

    cd $ GOPATH /上网

Use nano or your preferred text editor to create a file named main.go, which will contain the source code for your web application:

使用nano或您喜欢的文本编辑器创建一个名为main.go的文件,该文件将包含您的Web应用程序的源代码:

  • nano main.go

    纳米main.go

To create the functionality of the Hello World application, add the following Go code into the newly created main.go file:

要创建Hello World应用程序的功能,请将以下Go代码添加到新创建的main.go文件中:

~/go/go-web/main.go
〜/ go / go-web / main.go
package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello World")
    })

    http.HandleFunc("/greet/", func(w http.ResponseWriter, r *http.Request) {
        name := r.URL.Path[len("/greet/"):]
        fmt.Fprintf(w, "Hello %s\n", name)
    })

    http.ListenAndServe(":9990", nil)
}

Now let’s go through what the preceding code snippet will do, starting from the first line.

现在,让我们从第一行开始,浏览前面的代码片段的工作。

First, you wrote the entry point into your application:

首先,您将入口点写入了应用程序:

~/go/go-web/main.go
〜/ go / go-web / main.go
package main
...

The package main tells the Go compiler to compile this file as an executable program instead of as a shared library.

package main告诉Go编译器将此文件作为可执行程序而不是共享库进行编译。

Next, you have the import statements:

接下来,您将具有import语句:

~/go/go-web/main.go
〜/ go / go-web / main.go
...

import (
    "fmt"
    "net/http"
)
...

This snippet imports the necessary modules required for this code to work, which include the standard fmt package and the net/http package for your web server.

此代码段导入了此代码运行所需的必要模块,其中包括标准fmt软件包和Web服务器的net/http软件包。

The next snippet creates your first route in the main function, which is the entry point of any Go application:

下一个代码段在main函数中创建您的第一个路线,这是任何Go应用程序的入口点:

~/go/go-web/main.go
〜/ go / go-web / main.go
...
func main () {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello World")
    })
  ...
}
...

A parent route / is created within func main, which will return the text Hello World when requested.

func main创建了一个父路由/ ,当被请求时,它将返回文本Hello World

The second route as shown in the following snippet accepts a URL parameter, in this case a name, to display accompanied by a greeting.

如以下代码段所示,第二条路由接受一个URL参数(在本例中为name),并伴随问候语显示。

~/go/go-web/main.go
〜/ go / go-web / main.go
...
func main () {
  ...
    http.HandleFunc("/greet/", func(w http.ResponseWriter, r *http.Request) {
        name := r.URL.Path[len("/greet/"):]
        fmt.Fprintf(w, "Hello %s\n", name)
    })
...
}
...

This uses Go’s URL.Path to store the value right after /greet/ and pass it down as the name from the URL parameter.

它使用Go的URL.Path将值存储在/greet/ ,并将其作为URL参数的名称向下传递。

Finally, you instantiate your server:

最后,您实例化服务器:

~/go/go-web/main.go
〜/ go / go-web / main.go
...
func main () {
  ...
  http.ListenAndServe(":9990", nil)
}

The preceding snippet starts the server and exposes your application via port 9990 using Go’s inbuilt http server.

上面的代码片段启动了服务器,并使用Go的内置http服务器通过端口9990公开了您的应用程序。

Once you are finished examining the code in main.go, save the file and quit your text editor.

检查完main.go的代码后,保存文件并退出文本编辑器。

Next, build the binary executable of your application by running:

接下来,通过运行以下命令来构建应用程序的二进制可执行文件:

  • go build main.go

    去建立main.go

The preceding command will compile main.go to produce an executable titled main.

前面的命令将编译main.go以生成名为main的可执行文件。

You have created your sample Go web application. Next, you will create a systemd unit file to keep your application running in the background even when you are not accessing your server.

您已经创建了示例Go Web应用程序。 接下来,您将创建一个systemd单元文件,以使您的应用程序在后台运行,即使您不访问服务器也是如此。

第2步-创建系统单位文件 (Step 2 — Creating a Systemd Unit File)

In this step, you will create a systemd unit file to keep your application running in the background even when a user logs out of the server. This will make your application persistent, bringing you one step closer to a production-grade deployment.

在此步骤中,您将创建一个systemd单元文件,以使即使用户注销服务器,应用程序仍在后台运行。 这将使您的应用程序具有持久性,使您更接近生产级部署。

First, create a new file in /lib/systemd/system directory named goweb.service using nano or you preferred text editor:

首先,使用nano或您喜欢的文本编辑器在/lib/systemd/system目录中创建一个名为goweb.service的新文件:

  • sudo nano /lib/systemd/system/goweb.service

    须藤nano /lib/systemd/system/goweb.service

To set the parameters of the service, add the following snippet into the file.

要设置服务的参数,请将以下代码段添加到文件中。

/lib/systemd/system/goweb.service
/lib/systemd/system/goweb.service
[Unit]
Description=goweb

[Service]
Type=simple
Restart=always
RestartSec=5s
ExecStart=/home/user/go/go-web/main

[Install]
WantedBy=multi-user.target

The ExecStart=/home/user/go/go-web/main variable specifies that the point of entry for this service is through the main executable located in the /home/user/go/go-web directory, where user is the server non-root sudo account username. Restart=always ensures that systemd will always try to restart the program if it stops. On the next line, RestartSec=5s sets a five-second wait time between restart attempts. WantedBy=multi-user.target specifies in what state your server will enable the service.

ExecStart=/home/ user /go/go-web/main变量指定该服务的入口点是通过/home/ user /go/go-web目录中的main可执行文件执行的,其中user是服务器非root用户的sudo帐户用户名。 Restart=always确保systemd如果停止将始终尝试重新启动该程序。 在下一行, RestartSec=5s设置两次重启尝试之间的五秒钟等待时间。 WantedBy=multi-user.target指定服务器将以哪种状态启用该服务。

Save and exit the file.

保存并退出文件。

Now that you’ve written the service unit file, start your Go web service by running:

既然已经编写了服务单元文件,请通过运行以下命令启动Go Web服务:

  • sudo service goweb start

    sudo服务goweb启动

To confirm if the service is running, use the following command:

要确认服务是否正在运行,请使用以下命令:

  • sudo service goweb status

    sudo服务goweb状态

You’ll receive the following output:

您将收到以下输出:


   
   
Output
● goweb.service - goweb Loaded: loaded (/lib/systemd/system/goweb.service; disabled; vendor preset: enabled) Active: active (running) since Wed 2019-07-17 23:28:57 UTC; 6s ago Main PID: 1891 (main) Tasks: 4 (limit: 1152) CGroup: /system.slice/goweb.service └─1891 /home/user/go/go-web/main

To learn more about working with systemd unit file, take a look at Understanding Systemd Units and Unit Files.

要了解有关使用systemd单位文件的更多信息,请参阅了解Systemd单位和单位文件

Now that you have your application up and running, you can set up the Nginx reverse proxy.

现在您已经启动了应用程序并正在运行,您可以设置Nginx反向代理。

第3步—使用Nginx设置反向代理 (Step 3 — Setting Up a Reverse Proxy with Nginx)

In this step, you will create an Nginx server block and set up an Nginx reverse proxy to expose your application to the internet.

在此步骤中,您将创建一个Nginx服务器块并设置一个Nginx反向代理,以将您的应用程序公开到Internet。

First, change your working directory to the Nginx sites-available directory:

首先,将工作目录更改为Nginx sites-available目录:

  • cd /etc/nginx/sites-available

    cd / etc / nginx / sites-available

Create a new file with the name of the domain on which you wish to expose your application. This tutorial will use your_domain:

创建一个新文件,其中包含您希望在其上公开应用程序的域的名称。 本教程将使用your_domain

  • sudo nano your_domain

    须藤nano your_domain

Add the following lines into the file to establish the settings for your_domain:

your_domain添加到文件中,以建立your_domain的设置:

/etc/nginx/sites-available/your_domain
/ etc / nginx / sites-available / your_domain
server {
    server_name your_domain www.your_domain;

    location / {
        proxy_pass http://localhost:9990;
    }
}

This Nginx server block uses proxy_pass to serve the Go web application on your server’s IP address indicated as localhost to make it run on port 9990. server_name indicates the domain name mapped to your IP address, in this case your_domain and www.your_domain.

此Nginx服务器块使用proxy_pass在指示为localhost服务器IP地址上为Go Web应用程序提供服务,以使其在端口9990上运行。 server_name表示映射到您的IP地址的域名,在本例中为your_domainwww.your_domain

Next, create a symlink of this Nginx configuration in the sites-enabled folder by running the following command:

接下来,通过运行以下命令在sites-enabled文件夹中创建此Nginx配置的符号链接:

  • sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/your_domain

    sudo ln -s / etc / nginx / sites-available / your_domain / etc / nginx / sites-enabled / your_domain

A symlink is a shortcut of a file in another location. The newly created shortcut will always reference the original file to adjust to updates when edits are made to it. Nginx requires a copy of the configuration in both directories.

符号链接是文件在另一个位置的快捷方式。 新创建的快捷方式将始终引用原始文件,以在对其进行编辑时进行调整以进行更新。 Nginx在两个目录中都需要一份配置副本。

Next, reload your Nginx configurations by running the reload command:

接下来,通过运行reload命令来重新加载Nginx配置:

  • sudo nginx -s reload

    sudo nginx -s重新加载

To make sure that your deployment is working, visit http://your_domain in your browser. You will be greeted with a Hello World text string.

为确保您的部署正常进行,请在浏览器中访问http:// your_domain 。 您将看到Hello World文本字符串。

Note: As mentioned in the Prerequisites section, at this point it is recommended to enable SSL/TLS on your server. This will make sure that all communication between the application and its visitors will be encrypted, which is especially important if the application asks for sensitive information such as a login or password. Follow How To Secure Nginx with Let’s Encrypt on Ubuntu 18.04 now to obtain a free SSL certificate for Nginx on Ubuntu 18.04. After obtaining your SSL/TLS certificates, come back and complete this tutorial.

注意:如“先决条件”部分所述,此时建议在服务器上启用SSL / TLS。 这将确保应用程序及其访问者之间的所有通信都将被加密,如果应用程序要求输入诸如登录名或密码之类的敏感信息,这一点尤其重要。 立即关注如何在Ubuntu 18.04上使用“让我们加密”来保护Nginx,以在Ubuntu 18.04上获得Nginx的免费SSL证书。 获得SSL / TLS证书后,请返回并完成本教程。

You have now set up the Nginx reverse proxy to expose your application at your domain name, and secured your Go web application with SSL/TLS. In the next step, you will be testing your application over a secure connection.

现在,您已经设置了Nginx反向代理,以使用域名公开您的应用程序,并使用SSL / TLS保护Go Web应用程序。 在下一步中,您将通过安全连接测试您的应用程序。

步骤4 —测试应用程序 (Step 4 — Testing the Application)

In this step, you will test your application over a secure connection to make sure everything is working.

在此步骤中,您将通过安全连接测试您的应用程序,以确保一切正常。

Open your preferred web browser, visit https://your_domain:

打开您喜欢的网络浏览器,访问https:// your_domain

You will receive a simple Hello World message. Receiving this message when using https:// in the URL indicates that your application is being served over a secure connection.

您将收到一条简单的Hello World消息。 在URL中使用https://时收到此消息,表示正在通过安全连接为您的应用程序提供服务。

Next, try visiting the second route https://your_domain/greet/your-name, replacing your-name with whichever name you want your app to greet:

接下来,尝试访问第二条路线https:// your_domain /greet/ your-name ,将your-name替换为您希望应用程序问候的名称:

The application will return a simple greeting along with your-name, which is based on the parameter passed to the URL.

应用程序将返回简单的问候语和your-name ,后者基于传递给URL的参数。

Once you have received these results, you have successfully deployed your Go web application.

收到这些结果后,就可以成功部署Go Web应用程序。

结论 (Conclusion)

In this tutorial, you created a simple web application with Go using its standard libraries, set up a reverse proxy using Nginx, and used a SSL certificate on your domain to secure your app. To learn more about Go, check their official documentation. Also, you can look at our series How To Code in Go to learn more about programming in this efficient language.

在本教程中,您使用其标准库使用Go创建了一个简单的Web应用程序,使用Nginx设置了反向代理,并在您的域上使用SSL证书来保护您的应用程序。 要了解有关Go的更多信息,请查看其官方文档 。 另外,您可以查看我们的系列《 如何使用Go编写代码》,以了解更多有关使用这种高效语言进行编程的信息。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-go-web-application-using-nginx-on-ubuntu-18-04

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值