用docker弹性部署自己的服务

版权声明:本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。转载时请标注http://blog.csdn.net/marksinoberg. https://blog.csdn.net/Marksinoberg/article/details/83046189

很久不看docker的东西了,之前了解的一些基本命令都忘得差不多了,适逢工作需要,再来复习巩固下。今天想完成的是:借助docker不部署下自己的服务。

环境准备

都说“巧妇难为无米之炊”,所以还是需要先准备下的。

OS:Ubuntu 16.04, 2G内存
docker:1.13.2
coding language: golang (gin web framework)

编码

将服务跑起来,是我们要完成的第一个步骤,而且是最重要的一个步骤。所以这一步需要仔细调试,为了方便,我就写的简单点。

  1. app.go
package main

import (
	"os"
	"log"
		"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func GetHostName() string {
	hostname, err := os.Hostname()
	if err != nil {
		log.Fatal(err)
	}
	return hostname
}

func GetCurrentTime() string {
	timer := time.Now()
	return timer.String()
}

func startGinApp() {
	app := gin.Default()
	app.GET("/ping", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"message": "当前为您服务的主机为:" + GetHostName(),
		})
	})
	app.GET("/", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"message": "当前时间为:" + GetCurrentTime(),
		})
	})
	app.Run(":8080")
}

func main() {
	startGinApp()
}

  1. 把服务跑起来
go run app.go
  1. curl一下看看服务是否正确跑起来了
➜  gin curl http://localhost:8080
{"message":"当前时间为:2018-10-14 11:31:23.016121853 +0800 CST m=+0.254631109"}%                                                                                                 
➜  gin curl http://localhost:8080/ping
{"message":"当前为您服务的主机为:BiaodeMacBook-Pro.local"}%                                                                                                                      
➜  gin

制作Makefile

经过刚才的测试,代码可以正确跑起来了。但是要做到“一次编码,到处运行”,还是需要在构建阶段下点心思的,为了更好的维护,借助Makefile来规范构建过程,是比较合适的方法。

  1. Makefile
# 这个是注释
# 开头可以声明一大堆变量名
BUILD_NAME ?= httpserver
COMPILER ?= go
BUILD ?= build


# 上方留一个空格,区分变量区和构建区
all: build test deploy clean

build:
	CGO_ENABLED=0 GOOS=linux GOARCH=amd64 $(COMPILER) $(BUILD) -o $(BUILD_NAME)

test:
	echo "test over."

deploy:
	echo "deploy over."

clean:
	echo "clean over."

.PHONY: build test deploy clean


  1. 构建服务
➜  gin ls
Makefile app.go
➜  gin make all
go build -o httpserver
echo "test over."
test over.
echo "deploy over."
deploy over.
echo "clean over."
clean over.
➜  gin ls
Makefile   app.go     httpserver
➜  gin ./httpserver &
[1] 6450
➜  gin [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:	export GIN_MODE=release
 - using code:	gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /ping                     --> main.startGinApp.func1 (3 handlers)
[GIN-debug] GET    /                         --> main.startGinApp.func2 (3 handlers)
[GIN-debug] Listening and serving HTTP on :8080

➜  gin curl http://localhost:8080/ping
[GIN] 2018/10/14 - 11:50:23 | 200 |     214.161µs |             ::1 | GET      /ping
{"message":"当前为您服务的主机为:BiaodeMacBook-Pro.local"}%                                                                                                                      
➜  gin

好了基本没什么问题,然后就可以通过scp命令将文件拷贝到linux服务器上了。

制作Dockerfile

由于golang构建出来的是二进制可执行程序,所以制作Dockerfile很简单。

  1. Dockerfile
FROM ubuntu:latest

MAINTAINER guopu marksinoberg@gmail.com

WORKDIR /app

EXPOSE 8080

ADD . /app

CMD ["./httpserver"]
  1. 构建自己的镜像
root@Server218 /h/d/g/d/httpserver# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ginserver           latest              6277a0180f4f        19 hours ago        101 MB
flaskindocker       latest              170c6c0a41db        22 hours ago        131 MB
python              2.7-slim            14dad3ead5f4        4 days ago          120 MB
docker/compose      1.23.0-rc2          dc59a0b5e981        5 days ago          45.6 MB
ubuntu              latest              cd6d8154f1e1        5 weeks ago         84.1 MB
root@Server218 /h/d/g/d/httpserver# docker build -t httpserver .
Sending build context to Docker daemon 17.07 MB
Step 1/6 : FROM ubuntu:latest
 ---> cd6d8154f1e1
Step 2/6 : MAINTAINER guopu marksinoberg@gmail.com
 ---> Running in 7106748df3ad
 ---> 0ae808029537
Removing intermediate container 7106748df3ad
Step 3/6 : WORKDIR /app
 ---> 7278bf9659e7
Removing intermediate container f7fdc76b19a8
Step 4/6 : EXPOSE 8080
 ---> Running in bedfabcb4b16
 ---> edf4c123f72f
Removing intermediate container bedfabcb4b16
Step 5/6 : ADD . /app
 ---> 36390e554a2f
Removing intermediate container b14cce9da53e
Step 6/6 : CMD ./httpserver
 ---> Running in 6682c8364717
 ---> b490fef8a9ca
Removing intermediate container 6682c8364717
Successfully built b490fef8a9ca
root@Server218 /h/d/g/d/httpserver# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
httpserver          latest              b490fef8a9ca        4 seconds ago       101 MB
ginserver           latest              6277a0180f4f        19 hours ago        101 MB
flaskindocker       latest              170c6c0a41db        22 hours ago        131 MB
python              2.7-slim            14dad3ead5f4        4 days ago          120 MB
docker/compose      1.23.0-rc2          dc59a0b5e981        5 days ago          45.6 MB
ubuntu              latest              cd6d8154f1e1        5 weeks ago         84.1 MB
root@Server218 /h/d/g/d/httpserver#
  1. 让服务在docker中跑起来
root@Server218 /h/d/g/d/httpserver# docker run -d  -p 8000:8080 httpserver
ebb1926206cdaf16eae9f4e13d5a7e70dd695da91463b438f77e45c6f65d3323
root@Server218 /h/d/g/d/httpserver# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
ebb1926206cd        httpserver          "./httpserver"      4 seconds ago       Up 3 seconds        0.0.0.0:8000->8080/tcp   nostalgic_wright
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:ebb1926206cd"}~                                                                                                                                 

root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/
{"message":"当前时间为:2018-10-14 04:14:29.116207751 +0000 UTC"}~                                                                                                                

root@Server218 /h/d/g/d/httpserver#

至此,看起来服务已经成功在服务器环境下的docker中运行了。

弹性服务

一个容器跑一个服务,有些服务访问峰差很大的场景,就需要做下弹性适配,于是需要用一下docker swarm服务。这个在linux环境下需要进行安装。具体可以参考官网链接: https://github.com/docker/compose/releases
其运行以来一个YAML配置文件,具体细节不多说,上手吧。

  1. docker-compose.yml
version: "3"
services:
    web:
        image: httpserver:latest
        deploy:
            replicas: 5
            resources:
                limits:
                    cpus: "0.1"
                    memory: 50M
            restart_policy:
                condition: on-faliure
        ports:
            - "8000:8080"
        networks:
            - webnet
networks:
    webnet:
  1. 初始化swarm
root@Server218 /h/d/g/d/httpserver# docker swarm init
Swarm initialized: current node (atiuy6c8k1qcig5w3br1bwf0n) is now a manager.

To add a worker to this swarm, run the following command:

    docker swarm join \
    --token SWMTKN-1-5e0sj0glbwl5w5rqytyqokeg91n7piwdyw9ik598x0poiz5s20-do445zhrdr5io93lplov42c2y \
    172.31.237.68:2377

To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.

root@Server218 /h/d/g/d/httpserver#
  1. 发布服务到swarm中
root@Server218 /h/d/g/d/httpserver# docker stack deploy -c docker-compose.yml httpserver
Creating service httpserver_web
root@Server218 /h/d/g/d/httpserver#
root@Server218 /h/d/g/d/httpserver#
root@Server218 /h/d/g/d/httpserver#
root@Server218 /h/d/g/d/httpserver# docker stack ps httpserver
ID            NAME              IMAGE              NODE       DESIRED STATE  CURRENT STATE           ERROR  PORTS
kvpvwptlj44c  httpserver_web.1  httpserver:latest  Server218  Running        Running 14 seconds ago
6549g79dz5iz  httpserver_web.2  httpserver:latest  Server218  Running        Running 14 seconds ago
xkz42mnetmws  httpserver_web.3  httpserver:latest  Server218  Running        Running 14 seconds ago
rpziwzmpogn2  httpserver_web.4  httpserver:latest  Server218  Running        Running 14 seconds ago
y2kfe8bp09ld  httpserver_web.5  httpserver:latest  Server218  Running        Running 6 seconds ago
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:a5419e3d3f9c"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:f636819bd9c4"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:97a6e3c9a064"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:7f1b28e14970"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:0ce251661188"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver# curl http://localhost:8000/ping
{"message":"当前为您服务的主机为:a5419e3d3f9c"}~                                                                                                                                 
root@Server218 /h/d/g/d/httpserver#
  1. 实例弹性变化
    具体的操作只需要修改docker-compose.yml中的replicas的数量即可。然后重新使用:
docker stack deploy -c docker-compose.yml httpserver

发布就可以了,可以看出swarm管理下的实例会进行自动的负载均衡。

  1. 关停服务
root@Server218 /h/d/g/d/httpserver# docker stack ls
NAME        SERVICES
httpserver  1
root@Server218 /h/d/g/d/httpserver# docker stack rm httpserver
Removing service httpserver_web
Removing network httpserver_webnet
root@Server218 /h/d/g/d/httpserver# docker stack ls
NAME  SERVICES
root@Server218 /h/d/g/d/httpserver#
  1. 关掉swarm
root@Server218 /h/d/g/d/httpserver# docker swarm leave --force
Node left the swarm.
root@Server218 /h/d/g/d/httpserver#

总结

最后,回头看看这个目录。

root@Server218 /h/d/g/d/httpserver# ls -al
total 16688
drwxr-xr-x 2 root root     4096 Oct 14 12:20 ./
drwxr-xr-x 5 root root     4096 Oct 14 12:00 ../
-rw-r--r-- 1 root root      121 Oct 14 12:11 Dockerfile
-rw-r--r-- 1 root root      362 Oct 14 12:01 Makefile
-rw-r--r-- 1 root root      682 Oct 14 12:01 app.go
-rw-r--r-- 1 root root      385 Oct 14 12:27 docker-compose.yml
-rwxr-xr-x 1 root root 17063672 Oct 14 12:03 httpserver*
root@Server218 /h/d/g/d/httpserver#

基本上,在docker中弹性部署自己的服务就结束了,基本上也能满足需要。

阅读更多

扫码向博主提问

郭 璞

博客专家

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • 后台开发
  • PHP
  • Python
  • Java
去开通我的Chat快问
换一批

没有更多推荐了,返回首页