简体   繁体   中英

How to add an already build docker container to docker-compose?

I have a container called "postgres", build with plain docker command, that has a configured PostgreSQL inside it. Also, I have a docker-compose setup with two services - "api" and "nginx".

How to add the "postgres" container to my existing docker-compose setup as a service, without rebuilding? The PostgreSQL database is configured manually, and filled with data, so rebuilding is a really, really bad option.

I went through the docker-compose documentation, but found no way to do this without a re-build, sadly.

Unfortunately this is not possible.

You don't refer containers on docker-compose, you use images.

You need to create a volume and/or bind mount it to keep your database data.

This is because containers do not save data, if you have filled it with data and did not make a bind mount or a volume to it, you will lose everything on using docker container stop .

Recommendation:

docker cp

Docker cp will copy the contents from container to host. https://docs.docker.com/engine/reference/commandline/container_cp/

  1. Create a folder to save all your PostgreSQL data (ex: /home/user/postgre_data/)
  2. Save the contents of your PostgreSQL container data to this folder (docker hub postgres page for further reference: ;
  3. Run a new PostgreSQL (same version) container with a bind mount poiting to the new folder;

This will maintain all your data and you will be able to volume or bind mount it to use on docker-compose.

Reference of docker-compose volumes: https://docs.docker.com/compose/compose-file/#volumes

Reference of postgres docker image: https://hub.docker.com/_/postgres/

Reference of volumes and bind mounts: https://docs.docker.com/storage/bind-mounts/#choosing-the--v-or---mount-flag

You can save this container in a new image using docker container commit and use that newly created image in your docker-compose

docker container commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

I however prefer creating images with the use of Dockerfiles and scripts to fill my data etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM