macOS 27에서 vagrant ssh 포트가 바뀔 때

이번달에 나온 “요즘 개발자를 위한 쿠버네티스/도커” 책을 예약판매로 주문해서 받았습니다.

https://product.kyobobook.co.kr/detail/S000221973541

책에서는 virtualbox와 vagrant를 이용해서 실습 환경을 만드는데 책에 나온 버전 그대로 virtualbox 7.2.8, vagrant 2.4.9를 설치하고 vagrant up을 했더니 가상머신은 올라오는데 중간에 다음과 같은 메시지가 나왔습니다.

==> default: Fixed port collision for 22 => 2222. Now on port 2250.
    default: 22 (guest) => 2250 (host) (adapter 1)

사용하고 있는 포트가 아닌데 충돌이 났다고 하면서 2250으로 바꿔 버려서 책에 나온 포트로는 접속이 되지 않았습니다.

찾아보니 책 저장소에 이미 이슈가 올라와 있었고 macOS 26.7 이후에 생기는 문제라고 합니다.

https://github.com/sysnet4admin/_Book_k8sInfra/issues/48

이슈에 나와있는 방법대로 다음의 설정을 ~/.vagrant.d/Vagrantfile에 넣었습니다. (출처)

require "socket"
require "vagrant/util/is_port_open"

# Patch only hosts that actually misbehave, so this lapses by itself once macOS or Ruby is fixed.
socket_tcp_misreports_refusal = lambda do
  probe = TCPServer.new("127.0.0.1", 0)
  free_port = probe.addr[1]
  probe.close
  Socket.tcp("127.0.0.1", free_port, connect_timeout: 0.1).close
  true
rescue StandardError
  false
end

if socket_tcp_misreports_refusal.call
  module Vagrant
    module Util
      module IsPortOpen
        def is_port_open?(host, port)
          sock = Socket.tcp(host, port, connect_timeout: 0.1)
          begin
            sock.remote_address
            true
          rescue Errno::EINVAL, Errno::ENOTCONN
            false
          ensure
            sock.close
          end
        rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::EHOSTUNREACH,
               Errno::ENETUNREACH, Errno::EACCES, Errno::ENOTCONN, Errno::EALREADY
          false
        end

        extend IsPortOpen
      end
    end
  end
end

설정 후에 다시 시작하니 정상적으로 2222 포트로 돌아왔습니다.

$ vagrant reload
$ vagrant port
    22 (guest) => 2222 (host)

사용하는 맥은 macOS 27.2.1 입니다. 한번 넣어두면 모든 vagrant에 적용이 되어서 편했습니다.

기록을 위해 남겨둡니다.