How do I edit a file after I shell to a Docker container?

后端 未结 16 1771
你的背包
你的背包 2020-11-29 14:22

I successfully shelled to a Docker container using:

docker exec -i -t 69f1711a205e bash

Now I need to edit file and I don\'t have any edito

相关标签:
16条回答
  • 2020-11-29 14:54

    To keep your Docker images small, don't install unnecessary editors. You can edit the files over SSH from the Docker host to the container:

    vim scp://remoteuser@containerip//path/to/document
    
    0 讨论(0)
  • 2020-11-29 14:55

    It is kind of screwy, but in a pinch you can use sed or awk to make small edits or remove text. Be careful with your regex targets of course and be aware that you're likely root on your container and might have to re-adjust permissions.

    For example, removing a full line that contains text matching a regex:

    awk '!/targetText/' file.txt > temp && mv temp file.txt
    

    (More)

    0 讨论(0)
  • 2020-11-29 14:58

    You can just edit your file on host and quickly copy it into and run it inside the container. Here is my one-line shortcut to copy and run a Python file:

    docker cp main.py my-container:/data/scripts/ ; docker exec -it my-container python /data/scripts/main.py
    
    0 讨论(0)
  • 2020-11-29 15:04

    As in the comments, there's no default editor set - strange - the $EDITOR environment variable is empty. You can log in into a container with:

    docker exec -it <container> bash
    

    And run:

    apt-get update
    apt-get install vim
    

    Or use the following Dockerfile:

    FROM  confluent/postgres-bw:0.1
    
    RUN ["apt-get", "update"]
    RUN ["apt-get", "install", "-y", "vim"]
    

    Docker images are delivered trimmed to the bare minimum - so no editor is installed with the shipped container. That's why there's a need to install it manually.

    EDIT

    I also encourage you read my post about the topic.

    0 讨论(0)
  • 2020-11-29 15:06

    I use "docker run" (not "docker exec"), and I'm in a restricted zone where we cannot install an editor. But I have an editor on the Docker host.

    My workaround is: Bind mount a volume from the Docker host to the container (https://docs.docker.com/engine/reference/run/#/volume-shared-filesystems), and edit the file outside the container. It looks like this:

    docker run -v /outside/dir:/container/dir
    

    This is mostly for experimenting, and later I'd change the file when building the image.

    0 讨论(0)
  • 2020-11-29 15:07

    For common edit operations I prefer to install vi (vim-tiny), which uses only 1491 kB or nano which uses 1707 kB.

    In other hand vim uses 28.9 MB.

    We have to remember that in order for apt-get install to work, we have to do the update the first time, so:

    apt-get update
    apt-get install vim-tiny
    

    To start the editor in CLI we need to enter vi.

    0 讨论(0)
提交回复
热议问题