113

I need to add several lines to /etc/sysctl.conf in a Docker image.

Is there an idempotent way to do this via a Dockerfile rather than editing manually and using the docker commit approach?

Mike
  • 1,080
  • 1
  • 9
  • 25
Myles McDonnell
  • 12,943
  • 17
  • 66
  • 116

3 Answers3

183

I would use the following approach in the Dockerfile

RUN   echo "Some line to add to a file" >> /etc/sysctl.conf

That should do the trick. If you wish to replace some characters or similar you can work this out with sed by using e.g. the following:

RUN   sed -i "s|some-original-string|the-new-string |g" /etc/sysctl.conf

However, if your problem lies in simply getting the settings to "bite" this question might be of help.

Community
  • 1
  • 1
wassgren
  • 18,651
  • 6
  • 63
  • 77
17

sed work pretty well to replace stuff, if you need to append, you can user double redirect

sed -i 's/origin text/new text/g' /etc/sysctl.conf
bash -c 'echo hello world' >> /etc/sysctl.conf

-i is a non-standard option of GNU sed for inline editing (alleviating the need for dealing with temporary files).

The s is the substitute command of sed for find and replace

The g means global replace i.e. find all occurrences of origin text and replace with new text using sed

vvvvv
  • 25,404
  • 19
  • 49
  • 81
creack
  • 116,210
  • 12
  • 97
  • 73
1

To complement the answers that already explain how you can append a single line, you can append multiple lines to a file like this:

RUN echo -e '\
Hello World!\n\
This is an example on how to\n\
append multiple lines to a file from within a Dockerfile.'\
>> /etc/sysctl.conf

Use double quotes if you want to expand variables.

stackprotector
  • 10,498
  • 4
  • 35
  • 64