使用kubernetes中本地环境上的主机名连接到Docker容器

时间:2020-10-01 00:54:49

标签: docker kubernetes docker-compose dns

我有一个包含的kubernete docker-compose

@WithMockUser

理想情况下,我想通过诸如frontend - a web app running on port 80 backend - a node server for API running on port 80 database - mongodb 之类的主机名访问frontend,并且浏览器能够通过诸如http://frontend:80之类的主机名来访问backend ,这是客户端上的网络应用程序所必需的。

如何通过本地主机环境(windows)上的那些主机名访问容器?


http://backend:80

docker-compose.yml

1 个答案:

答案 0 :(得分:1)

我能够使用docker-compose别名和网络来解决这个问题,我能够将每个容器连接到同一开发网络。

match containers to hostnames

有3个主要组成部分:

  • 容器映射节点dns服务器-通过docker ps获取别名,并创建一个DNS服务器,该服务器将这些请求重定向到127.0.0.1(本地主机)
  • nginx反向代理容器-通过虚拟网络中的主机将主机映射到容器
  • 项目-每个项目都是一个docker-compose.yml,在端口80上运行的容器数量可能不受限制

clientA的docker-compose.yml

version: "3.8"
services:
    frontend:
        build: frontend
        container_name: clienta-frontend
        networks:
            default:
                aliases:
                    - clienta.test
    backend:
        build: backend
        container_name: clienta-backend
        networks:
            default:
                aliases:
                    - api.clienta.test
networks:
    default:
        external: true # connect to external network (see below for more)
        name: 'development' # name of external network

nginx代理docker-compose.yml

version: '3'
services: 
    parent:
        image: nginx:alpine
        volumes:
            - ./nginx.conf:/etc/nginx/nginx.conf
        ports:
            - "80:80" #map port 80 to localhost
        networks:
            - development
networks:
    development: #create network called development
        name: 'development'
        driver: bridge

DNS服务器

import dns from 'native-dns'
import { exec } from 'child_process'

const { createServer, Request } = dns
const authority = { address: '8.8.8.8', port: 53, type: 'udp' }
const hosts = {}

let server = createServer()

function command (cmd) {
    return new Promise((resolve, reject) => {
        exec(cmd, (err, stdout, stderr) => stdout ? resolve(stdout) : reject(stderr ?? err))
    })
}
async function getDockerHostnames(){
    let containersText = await command('docker ps --format "{{.ID}}"')
    let containers = containersText.split('\n')
    containers.pop()
    await Promise.all(containers.map(async containerID => {
        let json = JSON.parse(await command(`docker inspect ${containerID}`))?.[0]
        let aliases = json?.NetworkSettings?.Networks?.development?.Aliases || []
        aliases.map(alias => hosts[alias] = {
            domain: `^${alias}*`,
            records: [
                { type: 'A', address: '127.0.0.1', ttl: 100 }
            ]
        })
    }))
}

await getDockerHostnames()
setInterval(getDockerHostnames, 8000)

function proxy(question, response, cb) {
    var request = Request({
        question: question, // forwarding the question
        server: authority,  // this is the DNS server we are asking
        timeout: 1000
    })

    // when we get answers, append them to the response
    request.on('message', (err, msg) => {
        msg.answer.map(a => response.answer.push(a))
    });

    request.on('end', cb)
    request.send()
}

server.on('close', () => console.log('server closed', server.address()))
server.on('error', (err, buff, req, res) => console.error(err.stack))
server.on('socketError', (err, socket) => console.error(err))
server.on('request', async function handleRequest(request, response) {
    await Promise.all(request.question.map(question => {
        console.log(question.name)
        let entry = Object.values(hosts).find(r => new RegExp(r.domain, 'i').test(question.name))
        if (entry) {
            entry.records.map(record => {
                record.name = question.name;
                record.ttl = record.ttl ?? 600;
                return response.answer.push(dns[record.type](record));
            })
        } else {
            return new Promise(resolve => proxy(question, response, resolve))
        }
    }))

    response.send()
});

server.serve(53, '127.0.0.1');

不要忘记更新计算机的网络设置,以将127.0.0.1用作DNS服务器

dns服务器+ nginx代理的Git存储库,以备您查看实现:https://github.com/framework-tools/dockerdnsproxy