Write to a file on docker container gives error: No such file or directory

I am trying to execute the following command:

docker exec mydocker echo "hello" >> /usr/local/src/scores.txt

But it gives me the following error:

  • Do I need a docker-machine with dlite?
  • Connection Error when trying to talk with a VM through Docker api
  • Docker: Unable to commit a built docker image
  • Cannot get image on Docker - Network timed out [Windows]
  • Using composer with wordpress in docker
  • How to start Jenkins slave on docker-cloud?
  • No such file or directory
    

    But using the following command:

    docker exec -it mydocker bash
    

    I make sure that the file actually exists there. Is there something that I am missing here?

    Thanks

  • AWS Gogs deployment using Docker image
  • named docker volume not updating using docker-compose
  • Development workflow for server and client using Docker Compose?
  • Update a Docker Image on an EC2 Instance
  • Login docker container get return info:cannot set user id: Resource temporarily unavailable
  • docker linking how can both containers know each others ip
  • 2 Solutions collect form web for “Write to a file on docker container gives error: No such file or directory”

    Try wrapping the echo command in a command string:

    docker exec mydocker sh -c 'echo "hello" >> /usr/local/src/scores.txt'
    

    Verify file contents using:

    docker exec mydocker cat /usr/local/src/scores.txt
    

    There is a good reason for this: it’s being interpreted as two commands.

    The solution is as stacksonstacks posted – wrap your container commands in a single shell command:

        docker exec mydocker sh -c 'echo "hello" >> /usr/local/src/scores.txt'
    

    But why is it happening?

    The key is that you’ve used a bash operator. Similar to any time you run something like:

        echo one two >> file.txt
    

    The “>>” operator doesn’t get passed as an argument to echo (like “one” and “two” do). Instead it executes your echo command and appends its output to a file.

    In this case, the “>>” operator is doing the same to your docker exec, and trying to output the results to /usr/local/src/scores.txt and reporting that the directory does not exist (on the host, not the container).

    This means that if you ran:

        docker exec mydocker echo "hello" >> scores.txt
    

    You’d find scores.txt on your host, containing “hello” – the output from the command run on the container.
    And as a final test try:

        docker exec cf65263ed353 hostname && hostname
    

    You’ll see it prints the container’s hostname (its hash ID), followed by your own. The second command is run on the host.

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.