3

I created a docker image to run crontab based on the official nginx image.

FROM nginx

RUN apt-get update && apt-get -y install cron

CMD ["cron", "-f"]

If I don't set the last line CMD ["cron", "-f"], the crontab service can't start after running it as a container. But if I set it, nginx can't start.

docker build -t some-content-nginx .
docker run --name some-nginx -d -p 8080:80 some-content-nginx
(Nginx isn't running)

How to start these 2 services together?

iooi
  • 453
  • 2
  • 10
  • 23
  • 1
    You only run one process per container, and so you'd run a separate cron container (for example, [How to run a cron job inside a docker container?](https://stackoverflow.com/questions/37458287/how-to-run-a-cron-job-inside-a-docker-container)). Is there a specific reason you're trying to run them in the same container? – David Maze Dec 23 '20 at 13:08
  • Because I want to use `crontab` to monitor logrotate for nginx logs in one container. In other container it can't get nginx's pid. – iooi Dec 24 '20 at 00:54
  • You might consider the default `nginx` image setting that writes logs to the `docker logs` output, or bind-mounting a host directory over `/var/log/nginx`. Either of those would let you use a host-based log-management solution that doesn't need special support inside the container. – David Maze Dec 24 '20 at 01:19
  • This way can do it well: https://docs.docker.com/config/containers/multi-service_container/ – iooi Dec 24 '20 at 02:07

1 Answers1

0

One way to achieve this is to wrap the nginx image's entrypoint file in an entrypoint of you own, whose job is to start the cron service and then hand off to the standard docker-nginx entrypoint. The nginx image uses the entrypoint /docker-entrypoint.sh, so we just need to start cron and pass the command to that script, using an entrypoint like:

#!/bin/bash

cron && /docker-entrypoint.sh "$@"

Here's a simple Dockerfile that creates the necessary entrypoint and overrides the entrypoint in the base image:

FROM nginx

RUN apt-get update && \
    apt-get install -y \
        cron \
        && \
    echo '#!/bin/bash\n\ncron && /docker-entrypoint.sh "$@"' >> entrypoint-wrapper.sh && \
    chmod +x /entrypoint-wrapper.sh

ENTRYPOINT ["/entrypoint-wrapper.sh"]

# Have to reset CMD since it gets cleared when we set ENTRYPOINT
CMD ["nginx", "-g", "daemon off;"]

Sample run

$ docker run --name nginx-cron --detach nginx-cron
34301405f7b426022d9c286ff4e00f1c58570d76c5aba6b9f1c50ef698829976
$ docker exec nginx-cron service cron status
cron is running.
$ docker exec nginx-cron service nginx status
nginx is running.
kthompso
  • 1,823
  • 6
  • 15