How do I edit a file after I shell to a Docker con

2019-01-12 13:15发布

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 editors inside:

root@69f1711a205e:/# nano
bash: nano: command not found
root@69f1711a205e:/# pico
bash: pico: command not found
root@69f1711a205e:/# vi
bash: vi: command not found
root@69f1711a205e:/# vim
bash: vim: command not found
root@69f1711a205e:/# emacs
bash: emacs: command not found
root@69f1711a205e:/#

How do I edit files?

标签: docker
12条回答
再贱就再见
2楼-- · 2019-01-12 13:59

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.

查看更多
贼婆χ
3楼-- · 2019-01-12 14:00

See Stack Overflow question sed edit file in place

It would be a good option here, if:

  1. To modify a large file, it's impossible to use cat.
  2. Install Vim is not allowed or takes too long. My situation is using the MySQL 5.7 image when I want to change the my.cnf file, there is no vim, vi, and Vim install takes too long (China Great Firewall). sed is provided in the image, and it's quite simple. My usage is like

    sed -i /s/testtobechanged/textwanted/g filename

    Use man sed or look for other tutorials for more complex usage.

查看更多
来,给爷笑一个
4楼-- · 2019-01-12 14:07

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
查看更多
Fickle 薄情
5楼-- · 2019-01-12 14:09

After you shelled to the Docker container, just type:

apt-get update
apt-get install nano
查看更多
Melony?
6楼-- · 2019-01-12 14:10

You can use cat if it's installed, which will most likely be the case if it's not a bare/raw container. It works in a pinch, and ok when copy+pasting to a proper editor locally.

cat > file
# 1. type in your content
# 2. leave a newline at end of file
# 3. ctrl-c
cat file

cat will output each line on receiving a newline. Make sure to add a newline for that last line. ctrl-c sends a SIGINT for cat to exit gracefully.

Another option is something like infilter which injects a process into the container namespace with some ptrace magic: https://github.com/yadutaf/infilter

查看更多
Summer. ? 凉城
7楼-- · 2019-01-12 14:16

An easy way to edit a few lines would be:

echo "deb http://deb.debian.org/debian stretch main" > sources.list
查看更多
登录 后发表回答