Kellen
Kellen

Reputation: 611

Modifying a Docker container's ENTRYPOINT to run a script before the CMD

I'd like to run a script to attach a network drive every time I create a container in Docker. From what I've read this should be possible by setting a custom entrypoint. Here's what I have so far:

FROM ubuntu
COPY *.py /opt/package/my_code
RUN mkdir /efs && \
    apt-get install nfs-common -y && \
    echo "#!/bin/sh" > /root/startup.sh && \
    echo "mount -t nfs4 -o net.nfs.com:/ /nfs" >> /root/startup.sh && \
    echo "/bin/sh -c '$1'" >> /root/startup.sh && \
    chmod +x /root/startup.sh
WORKDIR /opt/package
ENV PYTHONPATH /opt/package
ENTRYPOINT ["/root/startup.sh"]

At the moment my CMD is not getting passed through properly to my /bin/sh line, but I'm wondering if there isn't an easier way to accomplish this?

Unfortunately I don't have control over how my containers will be created. This means I can't simply prepend the network mounting command to the original docker command.

Upvotes: 1

Views: 913

Answers (1)

sydpy
sydpy

Reputation: 35

From documentation:

CMD should be used as a way of defining default arguments for an ENTRYPOINT command or for executing an ad-hoc command in a container

So if you have an ENTRYPOINT specified, the CMD will be passed as additional arguments for it. It means that your entrypoint script should explicitly handle these arguments.

In your case, when you run :

docker run yourimage yourcommand

What is executed in your container is :

/root/startup.sh yourcommand

The solution is to add exec "$@" at the end of your /root/startup.sh script. This way, it will execute any command given as its arguments.

You might want to read about the ENTRYPOINT mechanisms and its interaction with CMD.

Upvotes: 1

Related Questions