首页 > 解决方案 > docker 容器使用 ssh 密钥将卷连接到远程服务器

问题描述

我最近一直在使用 Docker,而且我是 docker 新手,我已经设法为 nginx/php 和 mysql 设置容器。

我拥有位于单独服务器上的网站资产,并且我已经使用 sshfs 连接到相同的服务器,并且我能够在容器文件夹和远程文件夹之间传输文件。但这是使用密码完成的,现在我需要使用 ssh 密钥进行连接。

下面是 docker-compose 文件的示例


version: '3.5'

services:
  php-fpm:
    build:
      context: ./images/fpm
    working_dir: /var/www/html
    volumes:
      - ../<code_base>/:/var/www/html
      - sshfs_test:/var/www/html/public/assets

volumes:
  sshfs_test:
    name: "sshfs_test"
    driver: vieux/sshfs:latest
    driver_opts:
      sshcmd: "<server_user>@<server_ip>:/path/to/assets"
      password: "<my_password>"
      allow_other: ""

上面的示例有效,但我需要使用 ssh 私钥而不是密码进行连接。

标签: dockersshdocker-volumesshfs

解决方案


看看:https ://github.com/vieux/docker-volume-sshfs/issues/19#issuecomment-748609520

终于找到了在我的系统上实现它的正确方法(一个 rpi 作为服务器,一个 Mac 托管远程卷),因此不必共享我的密码。

  1. 使用 make all 安装 vieux/sshfs(正如@ogmundur 推荐的所有机器上,对我来说:rpi(我的服务器所在的位置)和 mac(共享我的卷)

  2. 确保已经完成了根密钥基因(对我而言:在 Pi 中),并确定 rsa 所在的文件夹:/root/.ssh/,确保已共享公钥(对我而言:mac),否则有看看:https ://www.raspberrypi.org/documentation/remote-access/ssh/passwordless.md )

  3. (对我来说 pi)docker plugin disable vieux/sshfs:next

  4. (对我来说 pi)docker plugin set vieux/sshfs sshkey.source=/root/.ssh/(见:https ://blog.raphaelpiccolo.com/post/850 )

  5. (对我来说 pi)docker plugin enable vieux/sshfs:next

  6. (在 pi 上对我来说)这是我docker-compose.yml要推出的:

    version: "3"
    
    services:
      myserver:
        image: nginx:latest
        ports:
          - "80:80"
        volumes:
          - COMMONVOLUME:/usr/share/nginx/html
    
      volumes:
        COMMONVOLUME:
          driver: "vieux/sshfs:next"
          driver_opts:
            sshcmd: @:/REMOTEPATH/WHERE/THE/FOLDER/TOBESYNCFORVOLUME/IS
            allow_other: ""
    

推荐阅读