sharpthor
sharpthor

Reputation: 525

docker-compose recreates a running container despite having a different container_name in the docker-compose.yml

I have a simple docker-compose.yml file:

services:
  app: 
    build: .
    image: team/repo:$VERSION
    ports:
      - "$PORT:3000" 
    container_name: myname-$VERSION
    volumes: 
      - $DB_PATH:/db
      - ./tmp:/tmp
    environment:
      DB_PATH: /db
volumes:
  db:
  tmp:

After I define e.g. VERSION=1.0.0 and PORT=80, I start the container with:

docker-compose up -d

And it creates a container "myname-1.0.0". Afterwards, if I re-export my env. var. e.g. VERSION=1.0.1 and PORT=8080 and rerun the command, it stops the running container and launches the new one "byname-1.0.1". But the message is:

Recreating myname-1.0.0 ... done

"docker ps" shows only the new container "myname-1.0.1", but I would expect to see both containers running on ports 80 and 8080, respectively; and from 2 different images "team/repo:1.0.0" and "team/repo:1.0.1", respectively.

What are the correct steps to have the 2 containers running side by side? I'd appreciate any pointers, thanks!

Upvotes: 2

Views: 988

Answers (2)

David Maze
David Maze

Reputation: 159781

Docker Compose uses labels on containers to remember which container goes with which compose file. The container names as such aren't used for this. (In early versions of fig this wasn't true, but since 2015 it has been.)

Compose has the notion of a project name. This has a couple of impacts. One is that the project name gets put in the container labels, so versions of the same docker-compose.yml deployed under different project names are considered different projects. Another is that there is a default for container_name: based on the project and service name.

So, this should work for you if you:

  1. Delete the container_name: and let Docker Compose construct a non-conflicting default for you; and

  2. Use the docker-compose -p option or $COMPOSE_PROJECT_NAME environment variable to explicitly specify the project name.

    VERSION=1.0.0 PORT=80 COMPOSE_PROJECT_NAME=project-100 \
      docker-compose up
    VERSION=1.0.1 PORT=8080 COMPOSE_PROJECT_NAME=project-101 \
      docker-compose up
    

Upvotes: 3

LinPy
LinPy

Reputation: 18608

you need to specify the arg build in your docker-compose like this:

services:
  app: 
    build:
      context: .
      args:
        - VERSION
    image: team/repo:$VERSION
    ports:
      - "$PORT:3000" 
    container_name: myname-$VERSION
    volumes: 
      - $DB_PATH:/db
      - ./tmp:/tmp
    environment:
      DB_PATH: /db
volumes:
  db:
  tmp:

and start it like this :

docker-compose up -d --build

Upvotes: 0

Related Questions