找到你要的答案

Q:Automatically enter only running docker container

Q:自动进入运行Docker容器

In the cloud, I have multiple instances, each running a container with a different random name, e.g.:

CONTAINER ID        IMAGE                              COMMAND                CREATED             STATUS              PORTS                        NAMES
5dc97950d924        aws_beanstalk/my-app:latest   "/bin/sh -c 'python    3 hours ago         Up 3 hours          80/tcp, 5000/tcp, 8080/tcp   jolly_galileo    

To enter them, I type:

sudo docker exec -it jolly_galileo /bin/bash

Is there a command or can you write a bash script to automatically execute the exec to enter the correct container?

在云中,我有多个实例,每个实例运行一个具有不同随机名称的容器,例如:

CONTAINER ID        IMAGE                              COMMAND                CREATED             STATUS              PORTS                        NAMES
5dc97950d924        aws_beanstalk/my-app:latest   "/bin/sh -c 'python    3 hours ago         Up 3 hours          80/tcp, 5000/tcp, 8080/tcp   jolly_galileo    

进入他们,我键入:

sudo docker exec -it jolly_galileo /bin/bash

有一个命令或者你可以写一个bash脚本来自动执行exec输入正确的容器?

answer1: 回答1:

"the correct container"?

To determine what is the "correct" container, your bash script would still need either the id or the name of that container.

For example, I have a function in my .bashrc:

deb() { docker exec -u git -it $1 bash; }

That way, I would type:

deb jolly_galileo

(it uses the account git, but you don't have to)

“正确的容器”?

确定“正确”的容器是什么,你的bash脚本仍然需要的ID或是容器的名称。

例如,我有一个功能在我的.bashrc:

deb() { docker exec -u git -it $1 bash; }

这样,我会键入:

deb jolly_galileo

(它使用的帐户,但你不需要)

answer2: 回答2:

Here's my final solution. It edits the instance's .bashrc if it hasn't been edited yet, prints out docker ps, defines the dock function, and enters the container. A user can then type "exit" if they want to access the raw instances, and "exit" again to quit ssh.

commands:
  bashrc:
    command:  if ! grep -Fxq "sudo docker ps" /home/ec2-user/.bashrc; then echo -e "dock() { sudo docker exec -it $(sudo docker ps -lq) bash; } \nsudo docker ps\ndock" >> /home/ec2-user/.bashrc; fi

这是我最后的解决方案。它编辑实例的.bashrc如果它没有被编辑,打印出泊坞窗PS,定义了码头功能,进入容器。用户可以键入“退出”如果他们想接近原始的情况下,和“退出”再次退出SSH。

commands:
  bashrc:
    command:  if ! grep -Fxq "sudo docker ps" /home/ec2-user/.bashrc; then echo -e "dock() { sudo docker exec -it $(sudo docker ps -lq) bash; } \nsudo docker ps\ndock" >> /home/ec2-user/.bashrc; fi
bash  docker