Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker exec - Write text to file in container

Tags:

bash

docker

I want to write a line of text to a textfile INSIDE a running docker container. Here's what I've tried so far:

docker exec -d app_$i eval echo "server.url=$server_url" >> /home/app/.app/app.config 

Response:

/home/user/.app/app.config: No such file or directory 

Second try:

cfg_add="echo 'server.url=$server_url' >> /home/user/.app/app.config" docker exec -i app_$i eval $cfg_add 

Response:

exec: "eval": executable file not found in $PATH 

Any ideas?

like image 424
jwi Avatar asked Feb 29 '16 15:02

jwi


People also ask

How do I edit files in a docker container?

To verify, use the cat command to print the contents inside the file. In this way, you can use any editor of your choice to edit files inside the container. If you already have a container running in the background, you can even use the Docker exec command to get access to the bash of the container.

What is pseudo tty docker?

A pseudo-TTY is a pair of character special files, a master file and a corresponding slave file. The master file is used by a networking application such as OMVS or rlogin. The corresponding slave file is used by the shell or the user's process to read and write terminal data.


1 Answers

eval is a shell builtin, whereas docker exec requires an external utility to be called, so using eval is not an option.

Instead, invoke a shell executable in the container (bash) explicitly, and pass it the command to execute as a string, via its -c option:

docker exec "app_$i" bash -c "echo 'server.url=$server_url' >> /home/app/.app/app.config" 

By using a double-quoted string to pass to bash -c, you ensure that the current shell performs string interpolation first, whereas the container's bash instance then sees the expanded result as a literal, as part of the embedded single-quoted string.


As for your symptoms:

  • /home/user/.app/app.config: No such file or directory was reported, because the redirection you intended to happen in the container actually happened in your host's shell - and because dir. /home/user/.app apparently doesn't exist in your host's filesystem, the command failed fundamentally, before your host's shell even attempted to execute the command (bash will abort command execution if an output redirection cannot be performed).

    • Thus, even though your first command also contained eval, its use didn't surface as a problem until your second command, which actually did get executed.
  • exec: "eval": executable file not found in $PATH happened, because, as stated, eval is not an external utility, but a shell builtin, and docker exec can only execute external utilities.

like image 176
mklement0 Avatar answered Oct 22 '22 14:10

mklement0