在运行 Docker 容器时保持 bash 脚本运行

问题描述

我正在尝试从 Docker 容器内部建立 SSH 隧道连接。

我创建了一个允许连接的简短 shh-tunnel.sh 脚本:

ssh-tunnel.sh

ssh -4 -q -f -T -M -N -L 127.0.0.1:5433:credentials:more_credentials USER@HOST

然后我从 .Dockerfile 内部运行它,如下所示:

FROM ubuntu:20.04

RUN apt-get update && apt-get install -y -qq python3 python3-pip openssh-client

ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get install -y postgresql postgresql-contrib

copY ssh-tunnel.sh .

(other things ...)

RUN chmod u+x ./ssh-tunnel.sh 
CMD ./ssh-tunnel.sh

当我运行 docker build 时,一切看起来都很好。 我的问题是...当我运行 docker run 时如何保持连接建立?

解决方法

从命令行中删除 -f。从 ssh 手册页:

 -f      Requests ssh to go to background just before command execution...

当不再有前台进程时,Docker 假定您的容器已完成。如果您的命令退出进入后台,Docker 会清理容器。


其次,您对 -L 的论证看起来有点古怪。端口转发的格式为-L <local_port>:<remote_address>:<remote_port>127.0.0.1:5433:credentials:more_credentials 应该会产生如下错误:

Bad local forwarding specification '127.0.0.1:5433:credentials:more_credentials'

你也想解决这个问题。