How to run 2 different commands from docker-compose command:

huangapple go评论90阅读模式
英文:

How to run 2 different commands from docker-compose command:

问题

我想在docker-compose中运行两个不同的命令来启动我的服务。

1)bash script.sh
2)config /etc/config.yaml

目前,我的docker-compose文件如下所示。我希望在config命令之后运行bash脚本。

docker-compose.yaml:

services:
   API:
        build: .
        ports:
            - 8080:8080
        environment:
         - "USER=${USER}"
         - "PASSWORD=${PASSWORD}"
        volumes:
            - ./conf/config.yaml:/etc/api.yaml
        command: ["-config", "/etc/api.yaml"]
英文:

I want to run 2 different commands for my service from docker-compose.

  1. bash script.sh
  2. config /etc/config.yaml

Currently, my docker-compose looks like the below. I want the bash script to run after the config command

docker-compose.yaml:

services:
   API:
        build: .
        ports:
            - 8080:8080
        environment:
         - "USER=${USER}"
         - "PASSWORD=${PASSWORD}"
        volumes:
            - ./conf/config.yaml:/etc/api.yaml
        command: ["-config", "/etc/api.yaml"]

答案1

得分: 3

写一个新的入口脚本。

#!/bin/bash

/bin/api "$@"

# 可能还有
source /script.sh

# 或者使用 exec
exec /script.sh

在构建镜像时将其复制到镜像中。

COPY --chmod=755 entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]

这样,你在compose文件中传递的参数将传递给/bin/api,然后执行你的脚本。

我不确定这是否真的有用。API命令似乎正在启动一个长时间运行的进程,所以你的脚本可能永远不会真正运行。

你也可以在入口脚本中做类似这样的操作。

#!/bin/bash

run_script(){
  sleep 5
  source /script.sh
}

run_script &

exec /bin/api "$@"

这样会隐藏来自脚本的错误,所以它并不是非常可靠。

这将在后台运行该函数,该函数会休眠5秒钟以给API启动的时间,然后在API运行时运行脚本。

不知道你的脚本在做什么,所以很难说哪种方法是好的解决方案。第二个建议确实有点不太正规。

英文:

Write a new entrypoint script.

#!/bin/bash

/bin/api "$@"

# perhaps
source /script.sh

# or exec
exec /script.sh

Copy this into your image on build.

COPY --chmod=755 entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]

This will result in the arguments you are passing in your compose file to be passed to /bin/api, and after that your script is executed.

I am not sure if that would be actually useful. The API command looks like it's initiating a long-running process, so your script might never really run.

You could also dome something like this in your entrypoint.

#!/bin/bash

run_script(){
  sleep 5
  source /script.sh
}

run_script &

exec /bin/api "$@"

It would hide errors from that script though, so its not really solid.

This would run the function in the background, which would sleep 5 seconds to give the API time to start, and then run the script while the API is running.

It's hard to say, without knowing what your script is doing, what would be a good solution. The second suggestion feels definitely a bit hacky.

huangapple
  • 本文由 发表于 2022年4月19日 03:56:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/71916469.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定