Docker Compose keep container running

I want to start a service with docker-compose and keep the container running so I can get its IP-address via 'docker inspect'. However, the container always exits right after starting up.

I tried to add "command: ["sleep", "60"]" and other things to the docker-compose.yml but whenever I add the line with "command:..." I cant call "docker-compose up" as I will get the message "Cannot start container ..... System error: invalid character 'k' looking for beginning of value"

I also tried adding "CMD sleep 60" and whatnot to the Dockerfile itself but these commands do not seem to be executed.

Is there an easy way to keep the container alive or to fix one of my problems?

EDIT: Here is the Compose file I want to run:

version: '2'
services:
  my-test:
    image: ubuntu
    command: bash -c "while true; do echo hello; sleep 2; done"

It's working fine If I start this with docker-compose under OS X, but if I try the same under Ubuntu 16.04 it gives me above error message.

If I try the approach with the Dockerfile, the Dockerfile looks like this:

FROM ubuntu:latest
CMD ["sleep", "60"]

Which does not seem to do anything

EDIT 2: I have to correct myself, turned out it was the same problem with the Dockerfile and the docker-compose.yml: Each time I add either "CMD ..." to the Dockerfile OR add "command ..." to the compose file, I get above error with the invalid character. If I remove both commands, it works flawlessly.


Solution 1:

To keep a container running when you start it with docker-compose, use the following command

command: tail -F anything

In the above command the last part anything should be included literally, and the assumption is that such a file is not present in the container, but with the -F option (capital -F not to be confused with -f which in contrast will terminate immediateley if the file is not found) the tail command will wait forever for the file anything to appear. A forever waiting process is basically what we need.

So your docker-compose.yml becomes

version: '2'
services:
  my-test:
    image: ubuntu
    command: tail -F anything

and you can run a shell to get into the container using the following command

docker exec -i -t composename_my-test_1 bash

where composename is the name that docker-compose prepends to your containers.

Solution 2:

You can use tty configuration option.

version: '3'

services:
  app:
    image: node:8
    tty: true           # <-- This option

Note: If you use Dockerfile for image and CMD in Dockerfile, this option won't work; however, you can use the entrypoint option in the compose file which clears the CMD from the Dockerfile.