使用Docker对Go应用程序进行容器化的最佳实践

Go applications and containers are made for each other. Go’s small application binary sizes are a perfect fit for the microservices deployment strategies that Docker and Kubernetes excel at delivering. This synergy is not without its challenges, though. So it’s important to understand container best practices and key concepts to avoid security pitfalls that can easily creep into your container images.

Go应用程序和容器是相辅相成的。Go的小程序二进制大小非常适合Docker和Kubernetes擅长的微服务部署策略。不过,这种协同作用并非没有挑战。因此,了解容器的最佳实践和关键概念很重要,以避免安全隐患,这些隐患很容易潜入你的容器镜像中。

In this article you will code up a sample Go application and learn how best to containerize it and run it securely.

在这篇文章中,你将编码一个Go应用程序的样本,并学习如何最好地将其容器化并安全地运行它。

Prerequisites

先决条件

To follow along with this tutorial, you’ll need to have Docker and Go installed on your machine and a basic familiarity with both. You can find introductory instructions and downloads for Docker on the orientation and setup page of the Docker documentation. Good tutorials for Go can be found in the official Go documentation, or by skipping to the Go installation page for Linux.

要跟上本教程,你需要在你的机器上安装Docker和Go,并对两者有基本的熟悉。你可以在Docker文档的方向和设置页面找到Docker的介绍性说明和下载。Go的优秀教程可以在官方Go文档中找到,或者跳到Linux的Go安装页面。

Create a sample Go application

创建一个Go应用程序的样本

To start, let’s create our Go API. First, navigate to the directory where you want your Go application to reside on your machine. Then, create a directory named “godocker.” In this godocker/ directory, run the following command to define your Go module:

首先,让我们来创建我们的Go API。首先,导航到你想让你的Go应用程序驻留在你的机器上的目录。然后,创建一个名为 "godocker "的目录。在这个godocker/ 目录中,运行以下命令来定义你的Go模块。

Next, create a file called “main.go” inside the “godocker” directory. This file will hold your API code. Now, you can add logic to provide and handle the current time via the API.

接下来,在 "godocker "目录下创建一个名为 "main.go "的文件。这个文件将保存你的API代码。现在,你可以添加逻辑,通过API提供和处理当前时间。

Enter the following code in godocker/main.go:

godocker/main.go 中输入以下代码。

package main

import (
"encoding/json"
"fmt"
"log"
"net/http"
) type Time struct {
CurrentTime string `json:...
开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.139.0. UTC+08:00, 2024-12-22 23:58
浙ICP备14020137号-1 $访客地图$