Docker:如果容器使用主机网络并且 vpn 已启动,则 gethostid 返回 0

问题描述 投票:0回答:1
如果我连接到办公室的 VPN,

gethostid 在 docker 容器中的行为会有所不同。

主机操作系统:Ubuntu 20.04

容器操作系统:Ubuntu 20.04

用于连接 VPN 的软件:SonicWall NetExtender 10.2.845(也用 8.6.801 复制)

Docker运行命令:

docker run -it --rm --network="host" test_gethostid_vpn:latest

在此容器中 gethostid 需要 5 秒才能返回 0。 如果删除 --network="host" 选项或停止 netExtender,问题就会消失。

main.cpp 在我的容器中运行:

#include <iostream>
#include <cstring>
#include <unistd.h>
#include <chrono>

int main(int* argc, char** argv)
{
    auto startPoint = std::chrono::steady_clock::now();
    long hostid = gethostid();
    auto endPoint = std::chrono::steady_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(endPoint - startPoint).count();
    std::cout << "duration = " << duration << " [ms]" << std::endl;
    std::cout << "hostid = " << hostid << std::endl;
    std::cout << "errno = " << std::strerror(errno) << std::endl;
    return 0;
}

CMakeLists.txt:

cmake_minimum_required(VERSION 3.16)

project(test_gethostid)

set(CMAKE_CXX_STANDARD 17)

add_executable(test_gethostid main.cpp)

Dockerfile:

FROM ubuntu:20.04

# Non interactive apt
# https://stackoverflow.com/questions/44331836/apt-get-install-tzdata-noninteractive
ENV TZ=Europe/Paris
ARG DEBIAN_FRONTEND=noninteractive

RUN apt-get update && apt-get upgrade -y && apt-get install -y cmake build-essential

COPY . /testcpp

WORKDIR /testcpp/build

RUN cmake ..
RUN make -j $(nproc)

ENTRYPOINT [ "./test_gethostid" ] 
c++ docker glibc ubuntu-20.04 libc
1个回答
0
投票

通过与容器共享 /etc/hostid 解决了问题:

docker run -it --rm -v /etc/hostid:/etc/hostid --network="host" test_gethostid_vpn:latest
© www.soinside.com 2019 - 2024. All rights reserved.