gpt4 book ai didi

docker - Golang Docker 容器未在 Docker-Compose 中重新启动

转载 作者:IT王子 更新时间:2023-10-29 02:28:24 34 4
gpt4 key购买 nike

我希望能够在无法连接到 rabbitmq 时重新启动 golang docker 文件,如此处所述:(Docker Compose wait for container X before starting Y 参见:svenhornberg 的回答)。不幸的是,我的 golang 容器将退出但永远不会重新启动,我不知道为什么。

Docker 撰写:

version: '3.3'
services:
mongo:
image: 'mongo:3.4.1'
container_name: 'datastore'
ports:
- '27017:27017'
rabbitmq:
restart: always
tty: true
image: rabbitmq:3.7-management-alpine
hostname: "rabbit"
ports:
- "15672:15672"
- "5672:5672"
labels:
NAME: "rabbitmq"
volumes:
- ./rabbitmq-isolated.conf:/etc/rabbitmq/rabbitmq.config
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:15672"]
interval: 3s
timeout: 5s
retries: 20
api:
restart: always
tty: true
container_name: 'api'
build: '.'
working_dir: /go/src/github.com/patientplatypus/project
ports:
- '8000:8000'
volumes:
- './:/go/src/github.com/patientplatypus/project'
- './uploads:/uploads'
- './scripts:/scripts'
- './templates:/templates'
depends_on:
- "mongo"
- "rabbitmq"

Docker 文件:

FROM golang:latest

WORKDIR /go/src/github.com/patientplatypus/project
COPY . .

RUN go get github.com/imroc/req
<...more go gets...>
RUN go get github.com/joho/godotenv

EXPOSE 8000

ENTRYPOINT [ "fresh" ]

这是我的 golang 代码:

package main

import (
"fmt"
"log"
"os"
"os/exec"
"net/http"
)

func main() {

fmt.Println("Golang server started")
godotenv.Load()
fmt.Println("now doing healthcheck on rabbit")
exec.Command("docker-compose restart api")
os.Exit(1)
<...>

这是我的终端输出(golang 在调用 rabbit 后从不重启):

api         | 23:23:00 app         | Golang server started
api | 23:23:00 app | now doing healthcheck on rabbit
rabbitmq_1 |
rabbitmq_1 | ## ##
rabbitmq_1 | ## ## RabbitMQ 3.7.11. Copyright (C) 2007-2019 Pivotal Software, Inc.
rabbitmq_1 | ########## Licensed under the MPL. See http://www.rabbitmq.com/
rabbitmq_1 | ###### ##
rabbitmq_1 | ########## Logs: <stdout>
<...more rabbit logging...>

我很困惑如何让它发挥作用。我做错了什么?

编辑:

exec.Command 未正确执行,但是 os.Exit(1)log.Fatallog。 Panic 退出容器,但容器没有重启。还是一头雾水。

最佳答案

The Docker documentation says:

A restart policy only takes effect after a container starts successfully. In this case, starting successfully means that the container is up for at least 10 seconds and Docker has started monitoring it. This prevents a container which does not start at all from going into a restart loop.

由于您显示的 Go 代码基本上立即退出,因此它永远不会满足这个最少 10 秒的规则。

您可以使用 time.After 强制 Go 等待,直到进程至少存活 10 秒。有点像:

ch := time.After(10 * time.Second)
defer (func() { fmt.Println("waiting"); <-ch; fmt.Println("waited") })()

也就是说,创建一个将在 10 秒后接收事件的 channel ,然后在 main 返回之前实际接收它(如果发生则立即接收,否则等待)。从玩https://play.golang.org/p/zGY5jFWbXyk ,一个技巧是在从 channel 接收后需要有一些可观察到的效果,否则它实际上不会等待。

关于docker - Golang Docker 容器未在 Docker-Compose 中重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54738691/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com