在容器内,特别是无需任何工具,确认端口是否开放的方法
Docker容器的映像,大部分都是使用slim和alpine制作的,包含了最基本的工具。因此,通常来说要确认某个端口是否开放,需要安装像nc或者telnet之类的工具。但是,如果有一种方法可以不使用工具来确认端口是否开放,那将非常方便。在这种情况下,您可以使用下面的命令。
printf "" > /dev/tcp/<ホスト名>/<ポート番号>
这个命令会尝试与指定的主机名和端口号建立TCP连接。如果连接成功,命令将无任何输出而结束。然而,如果连接失败,将会输出错误消息。
例如,如果要确认端口号为3000的端口是否打开,可以执行以下命令。
printf "" > /dev/tcp/localhost/3000
这个命令会尝试连接到本地主机(127.0.0.1)的3000端口。如果连接成功,将不会输出任何内容。然而,如果连接失败,则会显示以下错误消息。
bash: /dev/tcp/localhost/3000: Connection refused
只需要一个选项
bashとkshでしか動作せず、zshでは動作しません。
一部のディストリビューションではこの機能が無効になっている場合があります。
社内の方が確認してくださったが、ubuntu で apt changelog bashを確認してみたら、bash 2.04 の頃から無効になっていて (有効になったままリリースされたことがなくて)、bash 4.0 の頃から有効になっていたみたいです。
bash (2.04-5) unstable; urgency=low
* debian/patches/alpha-unwind.dpatch: Patch from "Mikolaj J. Habryn"
<fe78734e@eris.rcpt.to>. Should fix #62170, #62690, #65053.
* debian/rules: Configure with --disable-net-redirections (as suggested
in #65172). The patch submitted in the report can be found in
debian/patches/tcp-udp-service-names.dpatch.
* debian/patches/getcwd-error: Fix error message for two levels of
unreadable directories (#64659).
-- Matthias Klose <doko@debian.org> Mon, 5 Jun 2000 05:59:59 +0200
bash (4.0-5) unstable; urgency=low
* Re-add dependency on dash, lost with the upload of 4.0.
* Don't configure with --disable-net-redirections.
* Fix name of system wide bash_logout in bash(1). Closes: #546200.
* Stop shipping the sh and sh(1) symlinks. Closes: #545103.
* Apply upstream patches 029 - 033.
-- Matthias Klose <doko@debian.org> Sun, 13 Sep 2009 12:55:54 +0200
如果无效,您需要使用–enable-net-redirections选项重新编译bash,但在容器中重新编译会比较麻烦。然而,截至2023年4月6日,由于大多数Docker容器中bash的版本为5.1,所以大多数情况下应该可以正常工作。