version: '2'
services:
web:
container_name: myapp
build: .
command: node app.js
ports:
- "9000:3000"
The root cause lies in how docker-compose identifies services versus how containers are named. In your docker-compose.yml, you've defined the service as web
but assigned the container name as myapp
. This creates confusion when trying to reference the service.
Instead of:
docker-compose run myapp /bin/bash
You should use:
docker-compose run web /bin/bash
OR
docker exec -it myapp /bin/bash
For interactive shell access:
# Using docker-compose service name
docker-compose exec web sh
# Using container name directly
docker exec -it myapp sh
Here's a better approach for your docker-compose.yml:
version: '3'
services:
myapp: # Use same name for service and container
container_name: myapp
build: .
command: node app.js
ports:
- "9000:3000"
stdin_open: true # For interactive mode
tty: true # For terminal allocation
1. Verify services:
docker-compose ps
2. Check service names:
docker-compose config --services
3. If using custom container names, remember:
# docker-compose commands use SERVICE names
# docker commands use CONTAINER names
The error occurs because docker-compose run
expects a service name (defined in docker-compose.yml) rather than the container name. In your case, you're trying to use myapp
which is the container_name, while the actual service is named web
in the YAML file.
For Docker Compose operations, you should always reference the service name from your YAML file:
docker-compose run web /bin/bash
If you specifically need to work with the container name (perhaps in scripts where you only have the container name), you can use regular docker commands:
docker exec -it myapp /bin/bash
Here's a full example showing both methods with a Node.js application:
version: '3.8'
services:
web:
container_name: myapp
image: node:14
working_dir: /app
volumes:
- ./:/app
command: ["node", "server.js"]
ports:
- "9000:3000"
Error: Cannot create container for service web
- Usually indicates a port conflictError: No such container
- The container isn't running (usedocker-compose up -d
first)
1. Always keep service names in docker-compose.yml simple and meaningful
2. Use docker-compose ps
to verify running services
3. For production, consider using docker-compose exec
instead of run
for existing containers