将Docker容器链接到另一个子目录
我正在尝试设置多个可以通过一个主容器访问的Docker容器。
例如:
http://localhost:80
是主容器
http://localhost:80/site1
是一个单独的容器
http://localhost:80/site2
是一个单独的容器
我知道 – --link
标志已被弃用,而新的做法是使用--network
标志。
当我使用--link
(用于testing)时,我看到在主机文件中链接到的容器条目。 那是我卡住的地方。
所以我想使用docker –networking选项来设置上面的场景。
用例: /Site1
可能是一个网站的pipe理员区域或成员,但是我想将它们放在单独的容器中,这样我就可以更容易地维护它们。
这些容器是基于apache2的,但是如果可能的话,不想编辑任何configuration文件(但是如果我需要的话,我可以)
我会怎么做呢?
据我所知,docker没有办法将HTTP请求路由到一个或另一个容器。 您只能将主机上的端口映射到一个容器。
你将需要的是运行一个反向代理(例如nginx)作为你的主容器,然后将请求路由到适当的容器。
这里举一个例子如何设置它
SITE1 / Dockerfile
FROM node:6.11 WORKDIR /site1 COPY site1.js . CMD node site1.js EXPOSE 80
SITE1 / site1.js
var http = require("http"); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World 1\n'); }).listen(80);
站点2 / Dockerfile
FROM node:6.11 WORKDIR /site2 COPY site2.js . CMD node site2.js EXPOSE 80
站点2 / site2.js
var http = require("http"); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World 2\n'); }).listen(80);
节点代理/ default.conf
server { listen 80; # ~* makes the /site1 case insensitive location ~* /site1 { # Nginx can access the container by the service name # provided in the docker-compose.yml file. proxy_pass http://node-site1; } location ~* /site2 { proxy_pass http://node-site2; } # Anything that didn't match the patterns above goes here location / { # proxy_pass http://some other container return 500; } }
泊坞窗,compose.yml
version: "3" services: # reverse proxy node-proxy: image: nginx restart : always # maps config file into the proxy container volumes: - ./node-proxy/default.conf:/etc/nginx/conf.d/default.conf ports: - 80:80 links: - node-site1 - node-site2 # first site node-site1: build: ./site1 restart: always # second site node-site2: build: ./site2 restart: always
要启动反向代理服务器,两个站点都进入该文件夹的根目录docker-compose up -d
并使用docker ps -a
检查所有docker容器正在运行。
之后,您可以通过http:// localhost / site1和http:// localhost / site2访问这两个网站
说明
文件夹site1和site2包含一个带有nodejs的小型web服务器。 它们都在端口80上侦听。“node-proxy”包含告诉nginx何时返回哪个站点的configuration文件。
这里有一些链接
- docker-compose: https : //docs.docker.com/compose/overview/
- nginx反向代理: https : //www.nginx.com/resources/admin-guide/reverse-proxy/
你应该使用卷,所以你会像这样在docker-compose.yml
设置它
version: '3.2' services: container1: volumes: - shared-files:/directory/files container2: volumes: - shared-files:/directory/files container3: volumes: - shared-files:/directory/files volumes: shared-files: