How to use docker compose to build fastDFS file server

How to use docker compose to build fastDFS file server

The previous article introduced a detailed example of using docker compose to install the FastDfs file server.

Today I will introduce how to use docker compose to build a fastDFS file server. The details are as follows:

Platform: Mac M1

Note: About IP Address

Regarding the docker network mode, the above article mentions the docker Host 模式:

If you use the host mode when starting a container, the container will not obtain an independent Network Namespace, but will share a Network Namespace with the host. The container will not virtualize its own network card, configure its own IP, etc., but will use the host's IP and port. However, other aspects of the container, such as the file system and process list, are still isolated from the host machine.

The problem is: if you use the host machine's IP and port, and fill in localhost as the IP in the configuration file, you should be able to access the container, but in fact you can't. My personal understanding (please correct me if there is any misunderstanding) of how to fill in IP Address is as follows:

Console output when starting tracker :

The network of 192.168.64.2 is:

The network of 192.168.65.4 is:

File Directory

├── docker-compose.yaml
├── nginx
│ └── nginx.conf
├── storage
│ └── data
└── tracker
│ └── conf
│ └── client.conf
└── store_path

./docker-compose.yaml

version: "2"
services:
	fastdfs-tracker:
		hostname: fastdfs-tracker
		container_name: fastdfs-tracker
		image: season/fastdfs:1.2
		network_mode: "host"
		command: tracker
		volumes:
		  - ./tracker/data:/fastdfs/tracker/data
		  - ./tracker/conf:/etc/fdfs
	fastdfs-storage:
		hostname: fastdfs-storage
		container_name: fastdfs-storage
		image: season/fastdfs:1.2
		network_mode: "host"
		volumes:
		  - ./storage/data:/fastdfs/storage/data
		  - ./store_path:/fastdfs/store_path
		environment:
		  - TRACKER_SERVER=192.168.64.2:22122
		command: storage
		depends_on:
		  - fastdfs-tracker
	fastdfs-nginx:
		hostname: fastdfs-nginx
		container_name: fastdfs-nginx
		image: season/fastdfs:1.2
		network_mode: "host"
		volumes:
		  - ./nginx/nginx.conf:/etc/nginx/conf/nginx.conf
		  - ./store_path:/fastdfs/store_path
		environment:
		  - TRACKER_SERVER=192.168.64.2:22122
		command: nginx

./tracker/conf/client.conf

# connect timeout in seconds
# default value is 30s
connect_timeout=30
# network timeout in seconds
# default value is 30s
network_timeout=60

# the base path to store log files
base_path=/fastdfs/client

# tracker_server can ocur more than once, and tracker_server format is
# "host:port", host can be hostname or ip address
# Need to modify the ip here
tracker_server=192.168.64.2:22122

#standard log level as syslog, case insensitive, value list:
### emerg for emergency
### alert
### crit for critical
### error
### warn for warning
### notice
### info
### debug
log_level=info

# if use connection pool
# default value is false
# since V4.05
use_connection_pool = false

# connections whose the idle time exceeds this time will be closed
# unit: second
# default value is 3600
# since V4.05
connection_pool_max_idle_time = 3600

# if load FastDFS parameters from tracker server
# since V4.05
# default value is false
load_fdfs_parameters_from_tracker=false

# if use storage ID instead of IP address
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# default value is false
# since V4.05
use_storage_id = false

# specify storage ids filename, can use relative or absolute path
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# since V4.05
storage_ids_filename = storage_ids.conf

#HTTP settings
http.tracker_server_port=80

#use the "#include" directive to include HTTP other settings
##include http.conf

./nginx/nginx.conf

#user nobody;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;

events {
	worker_connections 1024;
}

http {
	include mime.types;
	default_type application/octet-stream;

	#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
	# '$status $body_bytes_sent "$http_referer" '
	# '"$http_user_agent" "$http_x_forwarded_for"';

	#access_log logs/access.log main;

	sendfile on;
	#tcp_nopush on;

	#keepalive_timeout 0;
	keepalive_timeout 65;

	#gzip on;

	server {
		listen 9800;
		server_name localhost;

		#charset koi8-r;

		#access_log logs/host.access.log main;

		# Modify part location / {
			root /fastdfs/store_path/data;
			ngx_fastdfs_module;
		}

		#error_page 404 /404.html;

		# redirect server error pages to the static page /50x.html
		#
		error_page 500 502 503 504 /50x.html;
		location = /50x.html {
			root html;
		}
	}
}

SpringBoot integrates fastDFS

Adding Dependencies

<dependency>
	<groupId>com.github.tobato</groupId>
	<artifactId>fastdfs-client</artifactId>
	<version>1.27.2</version>
</dependency>

application.yaml

# Distributed file system configuration fdfs:
  #Change the ip according to your own ip: 192.168.64.2
  #socket connection timeout soTimeout: 1500
  connectTimeout: 600
  #Support multiple trackerLists:
    - ${fdfs.ip}:22122
  # The ip and port of nginx in fastDFS
  # IDEA prompts to use https, 
  # nginx configure SSL please move to:
  web-server-url: http://${fdfs.ip}:9800/

FastDFSConfig.java

@Configuration
// Import FastDFS-Client component @Import(FdfsClientConfig.class)
//Solve the problem of repeated jmx bean registration @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public aspect FastDFSConfig {
}

FastDFSUtil.java

@Component
public class FastDFSUtil {
    @Resource
    private FastFileStorageClient fastFileStorageClient;
    @Resource
    private FdfsWebServer fdfsWebServer;

    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        String fullPath = storePath.getFullPath();
        getResAccessUrl(fullPath);
        return fullPath;
    }

    public String uploadFile(File file) {
        try {
            FileInputStream inputStream = new FileInputStream(file);
            StorePath storePath = fastFileStorageClient.uploadFile(inputStream, file.length(), FilenameUtils.getExtension(file.getName()), null);
            return storePath.getFullPath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public byte[] downloadFile(String filePath) {
        StorePath storePath = StorePath.parseFromUrl(filePath);
        return fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
    }

    public Boolean deleteFile(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return false;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(filePath);
            fastFileStorageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * Complete URL address of the package file*
     * @param path
     * @return
     */
    public String getResAccessUrl(String path) {
        return fdfsWebServer.getWebServerUrl() + path;
    }
}

FastDFSController.java

@RestController
@RequestMapping("/fast-dfs")
public class FastDFSController {
    /**
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("")
    @Transactional
    public void uploadFile(MultipartFile file, String cuisineId) throws IOException {
        String s = fastDfsUtil.uploadFile(file);
        String resAccessUrl = fastDfsUtil.getResAccessUrl(s);
    }

    /**
     * @param response
     * @throws IOException
     */
    @GetMapping("")
    public void downloadFile(String filePath, HttpServletResponse response) throws IOException {
        byte[] bytes = fastDfsUtil.downloadFile(filePath);

        String[] split = filePath.split("/");
        String fileName = split[split.length - 1];
        // Set force download to not open response.setContentType("application/force-download");

        fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        IOUtils.write(bytes, response.getOutputStream());
    }

    /**
     * Play the video in streaming mode, you can only watch from the beginning to the end, you cannot manually click to watch the content you have already watched* @param filePath
     * @param response
     * @throws IOException
     */
    @GetMapping("/play")
    public void streamMedia(String filePath, HttpServletResponse response) throws IOException {
        byte[] bytes = fastDfsUtil.downloadFile(filePath);
        IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
        response.flushBuffer();
    }
}

This is the end of this article about how to use docker compose to build a fastDFS file server. For more information about how to use docker compose to build fastDFS, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed example of installing FastDfs file server using docker compose
  • Some notes on installing fastdfs image in docker
  • Building FastDFS file system in Docker (multi-image tutorial)
  • How to install FastDFS in Docker
  • How to deploy FastDFS in Docker

<<:  MySQL5.7 single instance self-starting service configuration process

>>:  How to remove the "Enter" in the form, "Submit" and "Enter != Submit"

Recommend

Vue3.0 uses the vue-grid-layout plug-in to implement drag layout

Table of contents 1. Plugins 2. Interlude 3. Impl...

MySQL 5.7.17 installation and configuration tutorial under CentOS6.9

CentOS6.9 installs Mysql5.7 for your reference, t...

Introduction to the process of building your own FTP and SFTP servers

FTP and SFTP are widely used as file transfer pro...

ElementUI component el-dropdown (pitfall)

Select and change: click to display the current v...

A brief introduction to MySQL functions

Table of contents 1. Mathematical functions 2. St...

Practical record of handling MySQL automatic shutdown problems

I recently helped someone with a project and the ...

Summary of some situations when Docker container disk is full

Preface This article describes two situations I h...

VUE+SpringBoot implements paging function

This article mainly introduces how to implement a...

Super simple qps statistics method (recommended)

Statistics of QPS values ​​in the last N seconds ...

Detailed explanation of Nodejs array queue and forEach application

This article mainly records the problems and solu...

W3C Tutorial (8): W3C XML Schema Activities

XML Schema is an XML-based alternative to DTD. XM...

Specific use of Linux dirname command

01. Command Overview dirname - strip non-director...

uni-app WeChat applet authorization login implementation steps

Table of contents 1. Application and configuratio...

Dockerfile implementation code when starting two processes in a docker container

I want to make a docker for cron scheduled tasks ...