3

I have a docker-compose-custom.yml file like this:

version: '3.8'

services:
  myapp-back-preproduction:
    build:
      context: .
    container_name: myapp-back-preproduction
    image: 'myapp-back-preproduction:latest'
 ....

I want to execute a simple command within the container after this one started to run using docker-compose exec:

docker-compose -p myapp-back-preproduction -f docker-compose-custom.yml exec npm install

I expect npm install to be executed within the container.

But it displays nothing in the console, it simply returns.

docker exec instead works but it logically lacks all environment variables declared in my docker-compose-custom.yml file; I want to use docker-compose exec.

My docker-compose version is: 1.29.2

How to make it work?

1
  • I had a similar issue. In my case, docker-compose.yml passed some envvars through into the container. The shell from which I wanted to run docker-compose exec was lacking these envvars. Once I defined them, it ran successfully. Surprisingly running exec bash, envvars were using the values defined in the docker-compose up command's shell, not in the docker-compose exec bash shell. (Using docker-compose version 1.29.2, docker-compose.yml version 3.7) Nov 29, 2022 at 16:58

3 Answers 3

2

You messed up with the syntax.

$ docker-compose exec -h
Execute a command in a running container

Usage: exec [options] [-e KEY=VAL...] [--] SERVICE COMMAND [ARGS...]

Your command should be like:

docker-compose -f docker-compose-custom.yml exec myapp-back-preproduction npm install

-p switch is for specifying a project name: identifier that used to construct container name like <project_name>_<service_name>_1

1

You can use docker exec -it <container> <command> to execute a command in a running container (see docs). Notably, this enables you to start an interactive shell session within the container, which is really handy for all sorts of things.

I do wonder why you would need to call npm, though. If this is necessary to run your application, it should be done in the Dockerfile. (Alternatively it could be done in a start-up script.)

Do note that your container will only stay up while it is actually running an application (that is, while the entry point call did not return), so starting up an inactive container and then manually running applications won't work. The container would simply be stopped immediately.

0

this is sample command

docker-compose exec nginx apk add nodejs

it that command i try to install nodejs, so the command you need to execute

docker-compose exec container_namme npm install xxx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.