导语:笔记。使用redis和go进行容器间交互的测试
mani.go
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/gomodule/redigo/redis"
)
func main() {
addr := "0.0.0.0:80"
// var redisAddr = "127.0.0.1="
// var redisPort = "6379"
// var redisPassword = ""
// redis.Dial("tcp","redis:6379")
redisAddr, ok := os.LookupEnv("MY_REDIS_ADDR")
if !ok {
redisAddr = "127.0.0.1"
}
redisPort, ok := os.LookupEnv(("MY_REDIS_PORT"))
if !ok {
redisPort = "6379"
}
redisPassword, ok := os.LookupEnv(("MY_REDIS_PASSWORD"))
if !ok {
redisPassword = ""
}
redisClient, err := redis.Dial("tcp", fmt.Sprintf("%s:%s", redisAddr, redisPort), redis.DialPassword(redisPassword))
/* redisAddr := "redis:6379"
redisClient, err := redis.Dial("tcp", redisAddr) */
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
visit, _ := redis.Int(redisClient.Do("INCR", "visit"))
hostname, _ := os.Hostname()
// visit, _ := redis.Int(redisClient.Do("INCR", "visit"))
fmt.Fprintf(w, "%s: %s :%d", hostname, time.Now().Format("2006-01-02 15:04:05"), visit)
})
http.ListenAndServe(addr, nil)
}
Dockerfile
FROM ubuntu:18.04
MAINTAINER xujiamin
# 声明需要暴露的端口
EXPOSE 80
# web 编译结果是二进制文件
ADD web /opt/web/
ENTRYPOINT [ "/opt/web/web" ]
编译
docker run -it -v $PWD:/opt/web/ -e GOPROXY=https://goproxy.cn golang:1.17.6 bash -c "cd /opt/web;go get github.com/gomodule/redigo/redis;go build ."
docker build . -t woshidaxu/web:0.0.2
运行
docker run -itd --name web -p 9999:80 -e MY_REDIS_ADDR=redis --link=redis woshidaxu/web:0.0.2
b4a9601b7e8ee78cbe78e753f9d540ce9e522c00a16bf5d105c22e1f05b38ac2
直接通过curl访问 浏览器访问我这个数字是以2往上加的,应该是算上了favicon.ico
curl http://localhost:9999/
|