LoginSignup
2
0

More than 1 year has passed since last update.

ポートが開いているかどうかを確認する方法、ツールなしで、特にコンテナの中で便利

Last updated at Posted at 2023-04-06

Dockerコンテナのイメージは、ほとんどがslimalpineであり、必要最小限のツールが含まれています。そのため、ポート番号が開いているかどうかの確認には、通常はnctelnetなどのツールをインストールする必要があります。しかし、ツールを使用せずにポートが開いているかどうかを確認する方法があると便利ですよね。そのような場合は、以下のコマンドを使用できます。

printf "" > /dev/tcp/<ホスト名>/<ポート番号>

このコマンドは、指定したホスト名とポート番号にTCP接続を試みます。もし接続が成功した場合、何も出力されずにコマンドが終了します。一方、接続に失敗した場合は、エラーメッセージが出力されます。
例えば、ポート番号3000番が開いているかどうかを確認する場合、以下のコマンドを実行します。

printf "" > /dev/tcp/localhost/3000

このコマンドは、localhost(127.0.0.1)の3000番ポートに接続を試みます。もし接続が成功した場合、何も出力されません。一方、接続に失敗した場合は、以下のようなエラーメッセージが表示されます。

bash: /dev/tcp/localhost/3000: Connection refused

注意:

  • bashkshでしか動作せず、zshでは動作しません。
  • 一部のディストリビューションではこの機能が無効になっている場合があります。
    社内の方が確認してくださったが、ubuntuapt 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であるため、ほとんどの場合は問題なく動作すると考えられます。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0