Every service you define in your docker-compose.yml
corresponds to a container that docker-compose will start and manage. You can't "add an existing container" to a compose file.
If you want your compose services to interact with an existing container, you can certainly do that. The easiest mechanism is to ensure that your compose containers are on the same network as the existing container. For example, assuming you have an existing network named mynetwork
(created with docker network create mynetwork
), you would start your non-compose service like this:
docker run --network mynetwork ...
And you would write your compose file like this:
version: '3'
services:
db:
image: postgres:latest
environment:
- POSTGRES_PASSWORD=test
- POSTGRES_USER=test
- POSTGRES_DB=test
volumes:
- ./db_data:/var/lib/postgresql/data
networks:
mynetwork: {}
networks:
mynetwork:
external: true
This defines mynetwork
as an external network -- that is, one that has been created outside of Docker compose. By putting your compose containers on the same network as your existing container, they will be able to refer to eachother by name. That is, if your existing container is named dockerfiles_plugin-test_1
, then your db will be able to connect to it using the hostname dockerfiles_plugin-test_1
.
If you want to go in the other direction and have the dockerfiles_plugin-test_1
connect to the database, you probably want to set a static hostname (or alias) for the database container:
version: '3'
services:
db:
image: postgres:latest
environment:
- POSTGRES_PASSWORD=test
- POSTGRES_USER=test
- POSTGRES_DB=test
volumes:
- ./db_data:/var/lib/postgresql/data
networks:
mynetwork:
aliases:
- db
networks:
mynetwork:
external: true
This gives the db
container the hostname db
on network mynetwork
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…