使用bash脚本

时间:2017-01-13 22:10:54

标签: bash docker

由于我无法找到答案,我不确定我是否已将此标题做得很好我对使用类似术语感到非常满意,但现在就这样了。

在这种情况下,我们在docker容器中运行一些服务,而且他们都在各自的VLAN上运行。 Docker方便地为各种容器添加条目,以便应用程序可以从其容器名称中解析其他地址。例如。我有一个名为application的容器和一个运行mysql服务器的名为devsql的容器。如果我使用exec从应用程序容器运行ping devsql,它会解决问题并对其进行ping操作。但是,如果我从主机运行ping devsql,它就不知道那是什么。

我们的应用程序是一个laravel应用程序,我们编写迁移,然后我们使用' artisan'要执行的脚本。通常,这看起来像php artisan migrate。但是,配置使用devsql作为mysql服务器的地址,这对容器很好,但是主机无法解决这个问题,因此迁移会引发错误。

我们的解决方案是从vlan上的实用程序容器运行它,因此等效的命令将是docker run -it --rm --network=environment_network -v /var/www/html/whatever:/whatever util -c "cd /whatever && php artisan migrate"显然这最多是麻烦的,最坏的情况是混淆新员工。所以我想把它包装在一个脚本中。

我希望脚本能够像运行常规php一样工作。对于上面的示例,它非常简单,但我希望它能够处理例如php -r "echo 'lol'";。我不希望用户必须知道他们需要考虑多次扩展。我有一个可行的脚本,但我不确定它有多脆弱,我想知道是否有更好的方法来实现这个目标:

#!/bin/bash

# echo "cd /pwd && php $@"

# Assume that any argument with spaces in it was quoted (really not sure how great an assumption this
# is, but it's worked well in test).  Bash already expanded the string when parsing the command to call
# this script, but we want this to be a seamless experience for the user and they shouldn't have to know
# that it will be expanded twice, so we need to put quotes back around it.  Since we don't want to
# expand it here either, we surround it with single quotes to pass it to the docker container without
# expansion

x=()
for i in "$@"
do
        if [[ $i =~ [[:space:]] ]]
        then
                x+=\'$i\'' '
        else
                x+=$i' '
        fi
done

#echo "cd /pwd && php $x"

docker run -it --rm --network=environment_network -v $PWD:/pwd util -c "cd /pwd && php $x"

我只是从这个假设中获得了强大的代码味道,感觉就像一个黑客,并且必须有一个更好,更强大的方法来实现这一目标。或者说我的假设很差,而且我没有想到的东西会破坏它。

我想我的问题是,是否有内置构造以我想要的方式传递参数?或者你在我的假设中看到明显的缺陷吗?

1 个答案:

答案 0 :(得分:3)

使用-w选项更改工作目录,为命令使用单独的参数(php)并删除所有引用魔法:

docker run -it [other docker options] -w /pwd util php "$@"

这意味着图像中没有ENTRYPOINT(或者ENTRYPOINT可以处理所有这些参数)。否则,请使用--entrypoint /path/to/php,而不是将php指定为命令。