Docker容器未按Dockerfile配置安装Ansible的问题排查与解决
问题:Docker容器中Ansible命令找不到
我用包含Ansible安装配置的Dockerfile构建镜像,启动容器后执行ansible --version时出现bash: ansible: command not found错误。
原Dockerfile
FROM centos:centos7.7.1908 RUN yum check-update; \ yum install -y gcc libffi-devel python3 epel-release; \ yum install -y openssh-clients; \ yum install -y sshpass; \ yum clean all; \ pip3 install --upgrade pip RUN pip3 install "ansible==2.9.12"; \ pip3 install boto; \ pip3 install boto3; \ pip3 install "pywinrm>=0.3.0"
我执行docker build -t ansible:latest .构建镜像,进入容器后查看pip3 list,发现pywinrm、boto、boto3都已安装,但没有Ansible:
[root@7dbc2587a975 /]# pip3 list Package Version ------------------ --------- boto 2.49.0 boto3 1.23.10 botocore 1.26.10 certifi 2022.9.24 cffi 1.15.1 charset-normalizer 2.0.12 cryptography 38.0.4 idna 3.4 jmespath 0.10.0 ntlm-auth 1.5.0 pip 21.3.1 pycparser 2.21 python-dateutil 2.8.2 pywinrm 0.4.3 requests 2.27.1 requests-ntlm 1.1.0 s3transfer 0.5.2 setuptools 39.2.0 six 1.16.0 urllib3 1.26.13 xmltodict 0.13.0
尝试删除镜像重新构建(docker rmi ansible),问题依然存在。
修正后的可运行Dockerfile
FROM centos:centos7.7.1908 ENV LANG=en_US.UTF-8 ENV LC_ALL=en_US.UTF-8 RUN yum check-update; \ yum install -y gcc libffi-devel python3 epel-release; \ yum install -y openssh-clients; \ yum install -y sshpass; \ yum clean all; \ pip3 install --upgrade pip RUN pip3 install "ansible==2.9.12" && \ pip3 install boto && pip3 install boto3 && pip3 install "pywinrm>=0.3.0"
问题原因说明
- 命令执行逻辑问题:原Dockerfile的第二个RUN指令中使用分号
;分隔命令,这意味着即使pip3 install ansible执行失败,后续的pip安装命令仍会继续执行,导致Ansible实际未安装但其他依赖已装好的情况。改用&&后,只有前一个命令执行成功,后续命令才会运行,能及时暴露安装错误。 - 字符集环境缺失:添加
LANG和LC_ALL环境变量,避免因字符集问题导致Ansible安装过程中出现隐性错误。
内容的提问来源于stack exchange,提问作者Adrimus
相关产品推荐
相关产品推荐

