我曾经按照这些步骤连接到EC2容器实例,https://docs.aws.amazon.com/AmazonECS/latest/developerguide/instance-connect.html,现在想知道如何连接到FARGATE管理的容器实例。
我曾经按照这些步骤连接到EC2容器实例,https://docs.aws.amazon.com/AmazonECS/latest/developerguide/instance-connect.html,现在想知道如何连接到FARGATE管理的容器实例。
从2021年3月中旬开始,在AWS Fargate上运行容器时,可以执行ECS容器中的命令。请查阅博客文章“使用Amazon ECS Exec访问您在AWS Fargate和Amazon EC2上的容器”。
快速检查清单:
ssmmessages:..
权限添加到任务执行角色中。在实例内运行bash
的AWS CLI命令:
aws ecs execute-command \
--region eu-west-1 \
--cluster [cluster-name] \
--task [task id, for example 0f9de17a6465404e8b1b2356dc13c2f8] \
--container [container name from the task definition] \
--command "/bin/bash" \
--interactive
上述设置应允许运行/bin/bash
命令,并获得在运行于AWS Fargate的容器中获取交互式shell。有关详细信息,请查看文档“使用 Amazon ECS Exec 进行调试”。
浏览该github问题https://github.com/aws/amazon-ecs-cli/issues/143,我认为在ECS Fargate中无法从远程主机对容器进行docker exec操作。您可以尝试在一个容器中同时运行ssh守护进程和主进程(例如systemd)(https://docs.docker.com/config/containers/multi-service_container/),并使用SSH连接到您的容器,但一般来说,在容器世界中这不是个好主意。
允许在服务上执行命令。
aws ecs update-service --cluster <Cluster> --service <Service> --enable-execute-command
连接到 Fargate 任务。
aws ecs execute-command --cluster <Cluster> \
--task <taskId> \
--container <ContainerName> \
--interactive \
--command "/bin/sh"
参考 - https://docs.aws.amazon.com/zh_cn/AmazonECS/latest/developerguide/ecs-exec.html
以下是将SSH/sshd添加到容器中以获得直接访问的示例:
# Dockerfile
FROM alpine:latest
RUN apk update && apk add --virtual --no-cache \
openssh
COPY sshd_config /etc/ssh/sshd_config
RUN mkdir -p /root/.ssh/
COPY authorized-keys/*.pub /root/.ssh/authorized_keys
RUN cat /root/.ssh/authorized-keys/*.pub > /root/.ssh/authorized_keys
RUN chown -R root:root /root/.ssh && chmod -R 600 /root/.ssh
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
RUN ln -s /usr/local/bin/docker-entrypoint.sh /
# We have to set a password to be let in for root - MAKE THIS STRONG.
RUN echo 'root:THEPASSWORDYOUCREATED' | chpasswd
EXPOSE 22
ENTRYPOINT ["docker-entrypoint.sh"]
# docker-entrypoint.sh
#!/bin/sh
if [ "$SSH_ENABLED" = true ]; then
if [ ! -f "/etc/ssh/ssh_host_rsa_key" ]; then
# generate fresh rsa key
ssh-keygen -f /etc/ssh/ssh_host_rsa_key -N '' -t rsa
fi
if [ ! -f "/etc/ssh/ssh_host_dsa_key" ]; then
# generate fresh dsa key
ssh-keygen -f /etc/ssh/ssh_host_dsa_key -N '' -t dsa
fi
#prepare run dir
if [ ! -d "/var/run/sshd" ]; then
mkdir -p /var/run/sshd
fi
/usr/sbin/sshd
env | grep '_\|PATH' | awk '{print "export " $0}' >> /root/.profile
fi
exec "$@"
ecs exec
是否应该能够访问在 Fargate 上运行的任何容器,甚至那些部署到 EKS 集群(而不是 ECS)的容器吗?ecs exec
的文档根本没有提到 EKS,并且对这个问题非常模糊。 - timblaktu