docker 部署ipfs节点
# 创建docker ipfs 映射目录
% mkidr -p /Users/domino/files/ipfs/ipfs_node/ipfs_data
% mkdir -p /Users/domino/files/ipfs/ipfs_node/ipfs_staging
# 创建临时变量
% export ipfs_staging=/Users/jiangwujie/files/ipfs/ipfs_node/ipfs_staging
% export ipfs_data=/Users/jiangwujie/files/ipfs/ipfs_node/ipfs_data
# docker 启动 ipfs节点
% docker run -d --name ipfs_host -v $ipfs_staging:/export -v $ipfs_data:/data/ipfs -p 4001:4001 -p 8080:8080 -p 5001:5001 ipfs/go-ipfs:latest
# 查看ipfs容器
% docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
24b518cb8ad9 ipfs/go-ipfs:latest "/sbin/tini -- /usr/…" 35 minutes ago Up 35 minutes (healthy) 0.0.0.0:4001->4001/tcp, 0.0.0.0:5001->5001/tcp, 4001/udp, 0.0.0.0:8080->8080/tcp, 8081/tcp ipfs_host
使用nodejs进行本地图片上传测试
const ipfsAPI = require('ipfs-api');
// create an instance of the ipfs api client with the address of the local node
const ipfs = ipfsAPI('localhost', '5001', {
protocol: 'http'});
// read the image file from disk
const fs = require('fs');
const file = fs.readFileSync('/Users/domino/Downloads/jiagoutu.png');
// add the file to IPFS
ipfs.add(file, (err, result) => {
if (err) {
console.error(err);
return;
}
console.log('Image uploaded to IPFS. IPFS hash:', result[0].hash);
});
执行测试,可以看到上传成功
% node src/testipfs.js
{
'api-path': '/api/v0/',
'user-agent': '/node-ipfs-api/26.1.2/',
host: 'localhost',
port: '5001',
protocol: 'http'
}
Image uploaded to IPFS. IPFS hash: QmRXxBUN7rpGKRrE8sVxA5vzUd9JQTi4kDu2Nc4WctqaHX
使用这个hash值在浏览器上可以正常的获取图片进行展示
url为:http://localhost:8080/ipfs/{hash值}
如:http://localhost:8080/ipfs/QmRXxBUN7rpGKRrE8sVxA5vzUd9JQTi4kDu2Nc4WctqaHX
其他cors需要注意
如果在其他域名下使用js访问本地ipfs节点出现浏览器跨域的问题,如下:
Access to fetch at 'http://localhost:5001/api/v0/add?stream-channels=true' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
则需要修改本地ipfs节点配置,使其支持跨域访问,修改方式如下:
# 进入 ipfs docker容器
~ % docker exec -it 24b518cb8ad9 /bin/sh
# 执行命令修改ipfs配置
/ \# ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin '["*"]'
# 重启ipfs-host容器
~ % docker restart 24b518cb8ad9
随后即可正常进行请求
参考文档:
- https://blog.csdn.net/kk3909/article/details/104814337