night-gold
night-gold

Reputation: 2421

Importance of the place of CMD in Dockerfile

I have this Dockerfile that works fine, but I was told that maybe it wasn't the best way to do what I wanted :

FROM debian:jessie
RUN apt-get update && apt-get install -y lighttpd php5-cgi php5-common php5 php5-mysql php5-gd
RUN echo server.modules += \(\"mod_rewrite\"\) >> /etc/lighttpd/lighttpd.conf
CMD ["lighttpd", "-D", "-f", "/etc/lighttpd/lighttpd.conf"]
RUN lighty-enable-mod fastcgi-php
RUN service lighttpd restart
RUN chown -R www-data:www-data /var/www/html

As you can see, I am creating an image for a container with lighttpd and php.

My question is about the place of the CMD part in my Dockerfile. I was told that it was better to put it at the end of the file, but as you can see, I did it in the middle of mine and it worked just fine.

It does not stop the creation nor does it interfere with the service lighttpd restart in the run part below it.

Is there any best practice regarding this or is this normal? Could I create a Dockerfile with my CMD just after the apt-get install?

Thanks for your answers regarding my question and sorry for my english if there is any big mistakes.

Upvotes: 0

Views: 161

Answers (2)

ldg
ldg

Reputation: 9402

It shouldn't matter where you put the CMD entry in terms of Docker using that as the default command (plus Docker will use the last one if there is more than one). Where it might make a difference is if you were trying to structure your build in order to optimize caching the layers. I.e., you want to put anything that is likely to change lower down in the Dockerfile.

I think it's more convention to put it last and makes it easier to read. Is there a specific reason in your case you don't want to put it last?

Upvotes: 0

BMitch
BMitch

Reputation: 263469

I believe it's more of a logical preference, no need to define the command when the image isn't ready yet. There is an added convenience that debugging with the CMD or ENTRYPOINT set to a shell may make debugging a failed build a little easier. But otherwise, the last ENTRYPOINT and/or CMD modifies the config of the image and gets inherited to all child images (each line of your Dockerfile).

Upvotes: 1

Related Questions