Search code examples
dockerunixcrashexit

Restart Docker container on inner process crash


Update: Found secret cause - nodemon

The answer is just to set the container to restart on crash. In development, I'm using nodemon which prevents the process from exiting on a crash - so I assumed that the process crashing didn't cause the container to exit. My mistake. The process crashing does in fact cause the container to exit when using node and not nodemon.

{
  "scripts": {
    "development:service": "nodemon ./service/server.js",
    "production:service": "node ./service/server.js"
  }
}

Original Question

How do I restart a docker container when a process inside the container crashes?

Would the best way be to set --autorestart ON_FAILURE for the container and then make the container crash when the inner process crashes? If so, how do I force the container to crash when one of it's process crashes?

I'm using the image node:10.15.3.

Useful Link: how to make a container restart if the container, itself, crashes

Dockerfile

FROM node:10.15.3 

ENV NODE_ENV development

# Create application directory.
RUN mkdir -p /src
WORKDIR /src

# Install app dependencies and build.
ADD . /src
RUN yarn install --force

RUN ["chmod", "+x", "./run.sh"]
CMD [ "./run.sh" ]

Processes (simplified)

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
user        13  0.0  0.1  17952  2840 ?        S    15:09   0:00 bash ./install.sh
user        72  0.5  3.2 889668 66728 ?        Sl   15:09   0:00 /usr/local/bin/node /opt/yarn-v1.13.0/bin/yarn.js start 
user        97  2.4  3.2 919992 65748 ?        Sl   15:09   0:01 /usr/local/bin/node ./service/server.js

Solution

  • You can use the --restart flag for docker run command https://docs.docker.com/engine/reference/commandline/run/#restart-policies---restart

    Example: docker run --restart=on-failure my-image-name

    Or if you are using docker-compose then you restart: on-failure for the service https://docs.docker.com/compose/compose-file/#restart