diff --git a/src/tools/bash-memo/bash-memo.content.en.md b/src/tools/bash-memo/bash-memo.content.en.md deleted file mode 100644 index ef17e2435d..0000000000 --- a/src/tools/bash-memo/bash-memo.content.en.md +++ /dev/null @@ -1,573 +0,0 @@ -```bash -#!/bin/bash -############################################################################## -# SHORTCUTS and HISTORY -############################################################################## - -CTRL+A # move to beginning of line -CTRL+B # moves backward one character -CTRL+C # halts the current command -CTRL+D # deletes one character backward or logs out of current session, similar to exit -CTRL+E # moves to end of line -CTRL+F # moves forward one character -CTRL+G # aborts the current editing command and ring the terminal bell -CTRL+H # deletes one character under cursor (same as DELETE) -CTRL+J # same as RETURN -CTRL+K # deletes (kill) forward to end of line -CTRL+L # clears screen and redisplay the line -CTRL+M # same as RETURN -CTRL+N # next line in command history -CTRL+O # same as RETURN, then displays next line in history file -CTRL+P # previous line in command history -CTRL+Q # resumes suspended shell output -CTRL+R # searches backward -CTRL+S # searches forward or suspends shell output -CTRL+T # transposes two characters -CTRL+U # kills backward from point to the beginning of line -CTRL+V # makes the next character typed verbatim -CTRL+W # kills the word behind the cursor -CTRL+X # lists the possible filename completions of the current word -CTRL+Y # retrieves (yank) last item killed -CTRL+Z # stops the current command, resume with fg in the foreground or bg in the background - -ALT+B # moves backward one word -ALT+D # deletes next word -ALT+F # moves forward one word -ALT+H # deletes one character backward -ALT+T # transposes two words -ALT+. # pastes last word from the last command. Pressing it repeatedly traverses through command history. -ALT+U # capitalizes every character from the current cursor position to the end of the word -ALT+L # uncapitalizes every character from the current cursor position to the end of the word -ALT+C # capitalizes the letter under the cursor. The cursor then moves to the end of the word. -ALT+R # reverts any changes to a command you’ve pulled from your history if you’ve edited it. -ALT+? # list possible completions to what is typed -ALT+^ # expand line to most recent match from history - -CTRL+X then ( # start recording a keyboard macro -CTRL+X then ) # finish recording keyboard macro -CTRL+X then E # recall last recorded keyboard macro -CTRL+X then CTRL+E # invoke text editor (specified by $EDITOR) on current command line then execute resultes as shell commands -CTRL+A then D # logout from screen but don't kill it, if any command exist, it will continue - -BACKSPACE # deletes one character backward -DELETE # deletes one character under cursor - -history # shows command line history -!! # repeats the last command -! # refers to command line 'n' -! # refers to command starting with 'string' -esc :wq # exits and saves script - -exit # logs out of current session - - -############################################################################## -# BASH BASICS -############################################################################## - -env # displays all environment variables - -echo $SHELL # displays the shell you're using -echo $BASH_VERSION # displays bash version - -bash # if you want to use bash (type exit to go back to your previously opened shell) -whereis bash # locates the binary, source and manual-page for a command -which bash # finds out which program is executed as 'bash' (default: /bin/bash, can change across environments) - -clear # clears content on window (hide displayed lines) - - -############################################################################## -# FILE COMMANDS -############################################################################## - - -ls # lists your files in current directory, ls to print files in a specific directory -ls -l # lists your files in 'long format', which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified -ls -a # lists all files in 'long format', including hidden files (name beginning with '.') -ln -s # creates symbolic link to file -readlink # shows where a symbolic links points to -tree # show directories and subdirectories in easilly readable file tree -mc # terminal file explorer (alternative to ncdu) -touch # creates or updates (edit) your file -mktemp -t # make a temp file in /tmp/ which is deleted at next boot (-d to make directory) -cat # displays file raw content (will not be interpreted) -cat -n # shows number of lines -nl # shows number of lines in file -cat filename1 > filename2 # Copy filename1 to filename2 -cat filename1 >> filename2 # merge two files texts together -any_command > # '>' is used to perform redirections, it will set any_command's stdout to file instead of "real stdout" (generally /dev/stdout) -more # shows the first part of a file (move with space and type q to quit) -head # outputs the first lines of file (default: 10 lines) -tail # outputs the last lines of file (useful with -f option) (default: 10 lines) -vim # opens a file in VIM (VI iMproved) text editor, will create it if it doesn't exist -mv # moves a file to destination, behavior will change based on 'dest' type (dir: file is placed into dir; file: file will replace dest (tip: useful for renaming)) -cp # copies a file -rm # removes a file -find . -name # searches for a file or a directory in the current directory and all its sub-directories by its name -diff # compares files, and shows where they differ -wc # tells you how many lines, words and characters there are in a file. Use -lwc (lines, word, character) to ouput only 1 of those informations -sort # sorts the contents of a text file line by line in alphabetical order, use -n for numeric sort and -r for reversing order. -sort -t -k # sorts the contents on specific sort key field starting from 1, using the field separator t. -rev # reverse string characters (hello becomes olleh) -chmod -options # lets you change the read, write, and execute permissions on your files (more infos: SUID, GUID) -gzip # compresses files using gzip algorithm -gunzip # uncompresses files compressed by gzip -gzcat # lets you look at gzipped file without actually having to gunzip it -lpr # prints the file -lpq # checks out the printer queue -lprm # removes something from the printer queue -genscript # converts plain text files into postscript for printing and gives you some options for formatting -dvips # prints .dvi files (i.e. files produced by LaTeX) -grep # looks for the string in the files -grep -r # search recursively for pattern in directory -head -n file_name | tail +n # Print nth line from file. -head -y lines.txt | tail +x # want to display all the lines from x to y. This includes the xth and yth lines. - -sed 's///g' # replace pattern in file with replacement value to std output the character after s (/) is the delimeter -sed -i 's///g' # replace pattern in file with replacement value in place -echo "this" | sed 's/is/at/g' # replace pattern from input stream with replacement value - -############################################################################## -# DIRECTORY COMMANDS -############################################################################## - - -mkdir # makes a new directory -rmdir # remove an empty directory -rmdir -rf # remove a non-empty directory -mv # rename a directory from to -cd # changes to home -cd .. # changes to the parent directory -cd # changes directory -cp -r # copy into including sub-directories -pwd # tells you where you currently are -cd ~ # changes to home. -cd - # changes to previous working directory - -############################################################################## -# SSH, SYSTEM INFO & NETWORK COMMANDS -############################################################################## - - -ssh user@host # connects to host as user -ssh -p user@host # connects to host on specified port as user -ssh-copy-id user@host # adds your ssh key to host for user to enable a keyed or passwordless login - -whoami # returns your username -su # switch to a different user -su - # switch to root, likely needs to be sudo su - -sudo # execute command as the root user -passwd # lets you change your password -quota -v # shows what your disk quota is -date # shows the current date and time -cal # shows the month's calendar -uptime # shows current uptime -w # displays whois online -finger # displays information about user -uname -a # shows kernel information -man # shows the manual for specified command -info # shows another documentation system for the specific command -help # shows documentation about built-in commands and functions -df # shows disk usage -du # shows the disk usage of the files and directories in filename (du -s give only a total) -resize2fs # ext2/ext3/ext4 file system resizer -last # lists your last logins -ps -u yourusername # lists your processes -kill # kills the processes with the ID you gave -killall # kill all processes with the name -top # displays your currently active processes -lsof # lists open files -bg # lists stopped or background jobs ; resume a stopped job in the background -fg # brings the most recent job in the foreground -fg # brings job to the foreground - -ping # pings host and outputs results -whois # gets whois information for domain -dig # gets DNS information for domain -dig -x # reverses lookup host -wget # downloads file -netstat # Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships - -time # report time consumed by command execution - - -############################################################################## -# VARIABLES -############################################################################## - - -varname=value # defines a variable -varname=value command # defines a variable to be in the environment of a particular subprocess -echo $varname # checks a variable's value -echo $$ # prints process ID of the current shell -echo $! # prints process ID of the most recently invoked background job -echo $? # displays the exit status of the last command -read # reads a string from the input and assigns it to a variable -read -p "prompt" # same as above but outputs a prompt to ask user for value -column -t # display info in pretty columns (often used with pipe) -let = # performs mathematical calculation using operators like +, -, *, /, % -export VARNAME=value # defines an environment variable (will be available in subprocesses) -export -f # Exports function 'funcname' -export var1="var1 value" # Export and assign in the same statement -export # Copy Bash variable -declare -x # Copy Bash variable - -array[0]=valA # how to define an array -array[1]=valB -array[2]=valC -array=([2]=valC [0]=valA [1]=valB) # another way -array=(valA valB valC) # and another - -${array[i]} # displays array's value for this index. If no index is supplied, array element 0 is assumed -${#array[i]} # to find out the length of any element in the array -${#array[@]} # to find out how many values there are in the array - -declare -a # the variables are treated as arrays -declare -f # uses function names only -declare -F # displays function names without definitions -declare -i # the variables are treated as integers -declare -r # makes the variables read-only -declare -x # marks the variables for export via the environment -declare -l # uppercase values in the variable are converted to lowercase -declare -A # makes it an associative array - -${varname:-word} # if varname exists and isn't null, return its value; otherwise return word -${varname:word} # if varname exists and isn't null, return its value; otherwise return word -${varname:=word} # if varname exists and isn't null, return its value; otherwise set it word and then return its value -${varname:?message} # if varname exists and isn't null, return its value; otherwise print varname, followed by message and abort the current command or script -${varname:+word} # if varname exists and isn't null, return word; otherwise return null -${varname:offset:length} # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters - -${variable#pattern} # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest -${variable##pattern} # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest -${variable%pattern} # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest -${variable%%pattern} # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest -${variable/pattern/string} # the longest match to pattern in variable is replaced by string. Only the first match is replaced -${variable//pattern/string} # the longest match to pattern in variable is replaced by string. All matches are replaced - -${#varname} # returns the length of the value of the variable as a character string - -*(patternlist) # matches zero or more occurrences of the given patterns -+(patternlist) # matches one or more occurrences of the given patterns -?(patternlist) # matches zero or one occurrence of the given patterns -@(patternlist) # matches exactly one of the given patterns -!(patternlist) # matches anything except one of the given patterns - -$(UNIX command) # command substitution: runs the command and returns standard output - -typeset -l # makes variable local - must be an interger - -############################################################################## -# FUNCTIONS -############################################################################## - - -# The function refers to passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth. -# $@ is equal to "$1" "$2"... "$N", where N is the number of positional parameters. $# holds the number of positional parameters. - - -function functname() { - shell commands -} - -unset -f functname # deletes a function definition -declare -f # displays all defined functions in your login session - - -############################################################################## -# FLOW CONTROLS -############################################################################## - - -statement1 && statement2 # and operator -statement1 || statement2 # or operator - --a # and operator inside a test conditional expression --o # or operator inside a test conditional expression - -# STRINGS - -str1 == str2 # str1 matches str2 -str1 != str2 # str1 does not match str2 -str1 < str2 # str1 is less than str2 (alphabetically) -str1 > str2 # str1 is greater than str2 (alphabetically) -str1 \> str2 # str1 is sorted after str2 -str1 \< str2 # str1 is sorted before str2 --n str1 # str1 is not null (has length greater than 0) --z str1 # str1 is null (has length 0) - -# FILES - --a file # file exists or its compilation is successful --d file # file exists and is a directory --e file # file exists; same -a --f file # file exists and is a regular file (i.e., not a directory or other special type of file) --r file # you have read permission --s file # file exists and is not empty --w file # your have write permission --x file # you have execute permission on file, or directory search permission if it is a directory --N file # file was modified since it was last read --O file # you own file --G file # file's group ID matches yours (or one of yours, if you are in multiple groups) -file1 -nt file2 # file1 is newer than file2 -file1 -ot file2 # file1 is older than file2 - -# NUMBERS - --lt # less than --le # less than or equal --eq # equal --ge # greater than or equal --gt # greater than --ne # not equal - -if condition -then - statements -[elif condition - then statements...] -[else - statements] -fi - -for x in {1..10} -do - statements -done - -for name [in list] -do - statements that can use $name -done - -for (( initialisation ; ending condition ; update )) -do - statements... -done - -case expression in - pattern1 ) - statements ;; - pattern2 ) - statements ;; -esac - -select name [in list] -do - statements that can use $name -done - -while condition; do - statements -done - -until condition; do - statements -done - -############################################################################## -# COMMAND-LINE PROCESSING CYCLE -############################################################################## - - -# The default order for command lookup is functions, followed by built-ins, with scripts and executables last. -# There are three built-ins that you can use to override this order: `command`, `builtin` and `enable`. - -command # removes alias and function lookup. Only built-ins and commands found in the search path are executed -builtin # looks up only built-in commands, ignoring functions and commands found in PATH -enable # enables and disables shell built-ins - -eval # takes arguments and run them through the command-line processing steps all over again - - -############################################################################## -# INPUT/OUTPUT REDIRECTORS -############################################################################## - - -cmd1|cmd2 # pipe; takes standard output of cmd1 as standard input to cmd2 -< file # takes standard input from file -> file # directs standard output to file ->> file # directs standard output to file; append to file if it already exists ->|file # forces standard output to file even if noclobber is set -n>|file # forces output to file from file descriptor n even if noclobber is set -<> file # uses file as both standard input and standard output -n<>file # uses file as both input and output for file descriptor n -n>file # directs file descriptor n to file -n>file # directs file description n to file; append to file if it already exists -n>& # duplicates standard output to file descriptor n -n<& # duplicates standard input from file descriptor n -n>&m # file descriptor n is made to be a copy of the output file descriptor -n<&m # file descriptor n is made to be a copy of the input file descriptor -&>file # directs standard output and standard error to file -<&- # closes the standard input ->&- # closes the standard output -n>&- # closes the ouput from file descriptor n -n<&- # closes the input from file descriptor n - -|tee # output command to both terminal and a file (-a to append to file) - - -############################################################################## -# PROCESS HANDLING -############################################################################## - - -# To suspend a job, type CTRL+Z while it is running. You can also suspend a job with CTRL+Y. -# This is slightly different from CTRL+Z in that the process is only stopped when it attempts to read input from terminal. -# Of course, to interrupt a job, type CTRL+C. - -myCommand & # runs job in the background and prompts back the shell - -jobs # lists all jobs (use with -l to see associated PID) - -fg # brings a background job into the foreground -fg %+ # brings most recently invoked background job -fg %- # brings second most recently invoked background job -fg %N # brings job number N -fg %string # brings job whose command begins with string -fg %?string # brings job whose command contains string - -kill -l # returns a list of all signals on the system, by name and number -kill PID # terminates process with specified PID -kill -s SIGKILL 4500 # sends a signal to force or terminate the process -kill -15 913 # Ending PID 913 process with signal 15 (TERM) -kill %1 # Where %1 is the number of job as read from 'jobs' command. - -ps # prints a line of information about the current running login shell and any processes running under it -ps -a # selects all processes with a tty except session leaders - -trap cmd sig1 sig2 # executes a command when a signal is received by the script -trap "" sig1 sig2 # ignores that signals -trap - sig1 sig2 # resets the action taken when the signal is received to the default - -disown # removes the process from the list of jobs - -wait # waits until all background jobs have finished -sleep # wait # of seconds before continuing - -pv # display progress bar for data handling commands. often used with pipe like |pv -yes # give yes response everytime an input is requested from script/process - - -############################################################################## -# TIPS & TRICKS -############################################################################## - - -# set an alias -cd; nano .bash_profile -> alias gentlenode='ssh admin@gentlenode.com -p 3404' # add your alias in .bash_profile - -# to quickly go to a specific directory -cd; nano .bashrc -> shopt -s cdable_vars -> export websites="/Users/mac/Documents/websites" - -source .bashrc -cd $websites - - -############################################################################## -# DEBUGGING SHELL PROGRAMS -############################################################################## - - -bash -n scriptname # don't run commands; check for syntax errors only -set -o noexec # alternative (set option in script) - -bash -v scriptname # echo commands before running them -set -o verbose # alternative (set option in script) - -bash -x scriptname # echo commands after command-line processing -set -o xtrace # alternative (set option in script) - -trap 'echo $varname' EXIT # useful when you want to print out the values of variables at the point that your script exits - -function errtrap { - es=$? - echo "ERROR line $1: Command exited with status $es." -} - -trap 'errtrap $LINENO' ERR # is run whenever a command in the surrounding script or function exits with non-zero status - -function dbgtrap { - echo "badvar is $badvar" -} - -trap dbgtrap DEBUG # causes the trap code to be executed before every statement in a function or script -# ...section of code in which the problem occurs... -trap - DEBUG # turn off the DEBUG trap - -function returntrap { - echo "A return occurred" -} - -trap returntrap RETURN # is executed each time a shell function or a script executed with the . or source commands finishes executing - -############################################################################## -# COLORS AND BACKGROUNDS -############################################################################## -# note: \e or \x1B also work instead of \033 -# Reset -Color_Off='\033[0m' # Text Reset - -# Regular Colors -Black='\033[0;30m' # Black -Red='\033[0;31m' # Red -Green='\033[0;32m' # Green -Yellow='\033[0;33m' # Yellow -Blue='\033[0;34m' # Blue -Purple='\033[0;35m' # Purple -Cyan='\033[0;36m' # Cyan -White='\033[0;97m' # White - -# Additional colors -LGrey='\033[0;37m' # Light Gray -DGrey='\033[0;90m' # Dark Gray -LRed='\033[0;91m' # Light Red -LGreen='\033[0;92m' # Light Green -LYellow='\033[0;93m'# Light Yellow -LBlue='\033[0;94m' # Light Blue -LPurple='\033[0;95m'# Light Purple -LCyan='\033[0;96m' # Light Cyan - - -# Bold -BBlack='\033[1;30m' # Black -BRed='\033[1;31m' # Red -BGreen='\033[1;32m' # Green -BYellow='\033[1;33m'# Yellow -BBlue='\033[1;34m' # Blue -BPurple='\033[1;35m'# Purple -BCyan='\033[1;36m' # Cyan -BWhite='\033[1;37m' # White - -# Underline -UBlack='\033[4;30m' # Black -URed='\033[4;31m' # Red -UGreen='\033[4;32m' # Green -UYellow='\033[4;33m'# Yellow -UBlue='\033[4;34m' # Blue -UPurple='\033[4;35m'# Purple -UCyan='\033[4;36m' # Cyan -UWhite='\033[4;37m' # White - -# Background -On_Black='\033[40m' # Black -On_Red='\033[41m' # Red -On_Green='\033[42m' # Green -On_Yellow='\033[43m'# Yellow -On_Blue='\033[44m' # Blue -On_Purple='\033[45m'# Purple -On_Cyan='\033[46m' # Cyan -On_White='\033[47m' # White - -# Example of usage -echo -e "${Green}This is GREEN text${Color_Off} and normal text" -echo -e "${Red}${On_White}This is Red test on White background${Color_Off}" -# option -e is mandatory, it enable interpretation of backslash escapes -printf "${Red} This is red \n" -``` \ No newline at end of file diff --git a/src/tools/bash-memo/bash-memo.vue b/src/tools/bash-memo/bash-memo.vue index b50f1f1002..b8e9003bde 100644 --- a/src/tools/bash-memo/bash-memo.vue +++ b/src/tools/bash-memo/bash-memo.vue @@ -12,7 +12,7 @@ const memoComponent = ref(null); async function loadMemo(currentLocale = locale.value) { const memoKey = `./bash-memo.content.${currentLocale}.md`; - const loader = memoImports[memoKey] ?? memoImports['./bash-memo.content.en.md']; + const loader = memoImports[memoKey] ?? memoImports['./bash-memo.content.md']; if (!loader) { memoComponent.value = null; diff --git a/src/tools/css-selectors-memo/css-selectors-memo.vue b/src/tools/css-selectors-memo/css-selectors-memo.vue index 22127c009d..5802fe66b7 100644 --- a/src/tools/css-selectors-memo/css-selectors-memo.vue +++ b/src/tools/css-selectors-memo/css-selectors-memo.vue @@ -1,13 +1,36 @@ diff --git a/src/tools/css-selectors-memo/css-selectors.zh.md b/src/tools/css-selectors-memo/css-selectors.zh.md new file mode 100644 index 0000000000..2fabca68cd --- /dev/null +++ b/src/tools/css-selectors-memo/css-selectors.zh.md @@ -0,0 +1,63 @@ +| 选择器 | 示例 | 示例说明 | +|-----------------------|-------------------------|----------------------------------------------------------------------------------------------------------| +| `.class` | `.intro` | 选择所有 class="intro" 的元素 | +| `.class1.class2` | `.name1.name2` | 选择 class 属性中同时设置了 name1 和 name2 的所有元素 | +| `.class1 .class2` | `.name1 .name2` | 选择所有 name2 元素,且这些元素是 name1 元素的后代 | +| `#id` | `#firstname` | 选择 id="firstname" 的元素 | +| `*` | `*` | 选择所有元素 | +| `element` | `p` | 选择所有 \ 元素 | +| `element.class` | `p.intro` | 选择所有 class="intro" 的 \ 元素 | +| `element,element` | `div, p` | 选择所有 \ 元素和所有 \ 元素 | +| `element element` | `div p` | 选择 \ 元素内的所有 \ 元素 | +| `element>element` | `div > p` | 选择父元素为 \ 的所有 \ 元素 | +| `element+element` | `div + p` | 选择紧接在 \ 元素之后的第一个 \ 元素 | +| `element1~element2` | `p ~ ul` | 选择前面有 \ 元素的每个 \ 元素 | +| `[attribute]` | `[target]` | 选择所有带有 target 属性的元素 | +| `[attribute=value]` | `[target="_blank"]` | 选择所有 target="_blank" 的元素 | +| `[attribute~=value]` | `[title~="flower"]` | 选择所有 title 属性包含 "flower" 一词的元素 | +| `[attribute\|=value]` | `[lang\|="en"]` | 选择所有 lang 属性值等于 "en" 或以 "en-" 开头的元素 | +| `[attribute^=value]` | `a[href^="https"]` | 选择 href 属性值以 "https" 开头的每个 \ 元素 | +| `[attribute$=value]` | `a[href$=".pdf"]` | 选择 href 属性值以 ".pdf" 结尾的每个 \ 元素 | +| `[attribute*=value]` | `a[href*="w3schools"]` | 选择 href 属性值包含子串 "w3schools" 的每个 \ 元素 | +| `:active` | `a:active` | 选择激活状态的链接 | +| `::after` | `p::after` | 在每个 \ 元素的内容之后插入内容 | +| `::before` | `p::before` | 在每个 \ 元素的内容之前插入内容 | +| `:checked` | `input:checked` | 选择每个被选中的 \ 元素 | +| `:default` | `input:default` | 选择默认的 \ 元素 | +| `:disabled` | `input:disabled` | 选择每个被禁用的 \ 元素 | +| `:empty` | `p:empty` | 选择每个没有子元素(包括文本节点)的 \ 元素 | +| `:enabled` | `input:enabled` | 选择每个可用的 \ 元素 | +| `:first-child` | `p:first-child` | 选择每个作为其父元素第一个子元素的 \ 元素 | +| `::first-letter` | `p::first-letter` | 选择每个 \ 元素的第一个字母 | +| `::first-line` | `p::first-line` | 选择每个 \ 元素的第一行 | +| `:first-of-type` | `p:first-of-type` | 选择每个作为其父元素第一个 \ 元素的 \ 元素 | +| `:focus` | `input:focus` | 选择获得焦点的 input 元素 | +| `:fullscreen` | `:fullscreen` | 选择处于全屏模式的元素 | +| `:has()` | `h2:has(+p)` | 选择紧跟着 p 元素的 h2 元素,并将样式应用于 h2 | +| `:hover` | `a:hover` | 选择鼠标悬停时的链接 | +| `:in-range` | `input:in-range` | 选择值在特定范围内的 input 元素 | +| `:indeterminate` | `input:indeterminate` | 选择处于不确定状态的 input 元素 | +| `:invalid` | `input:invalid` | 选择所有值无效的 input 元素 | +| `:lang()` | `p:lang(it)` | 选择每个 lang 属性等于 "it"(意大利语)的 \ 元素 | +| `:last-child` | `p:last-child` | 选择每个作为其父元素最后一个子元素的 \ 元素 | +| `:last-of-type` | `p:last-of-type` | 选择每个作为其父元素最后一个 \ 元素的 \ 元素 | +| `:link` | `a:link` | 选择所有未访问的链接 | +| `::marker` | `::marker` | 选择列表项的标记 | +| `:not()` | `:not(p)` | 选择每个不是 \ 元素的元素 | +| `:nth-child()` | `p:nth-child(2)` | 选择每个作为其父元素第二个子元素的 \ 元素 | +| `:nth-last-child()` | `p:nth-last-child(2)` | 选择每个作为其父元素第二个子元素的 \ 元素,从最后一个子元素开始计数 | +| `:nth-last-of-type()` | `p:nth-last-of-type(2)` | 选择每个作为其父元素第二个 \ 元素的 \ 元素,从最后一个子元素开始计数 | +| `:nth-of-type()` | `p:nth-of-type(2)` | 选择每个作为其父元素第二个 \ 元素的 \ 元素 | +| `:only-of-type` | `p:only-of-type` | 选择每个作为其父元素唯一 \ 元素的 \ 元素 | +| `:only-child` | `p:only-child` | 选择每个作为其父元素唯一子元素的 \ 元素 | +| `:optional` | `input:optional` | 选择没有 "required" 属性的 input 元素 | +| `:out-of-range` | `input:out-of-range` | 选择值超出特定范围的 input 元素 | +| `::placeholder` | `input::placeholder` | 选择指定了 "placeholder" 属性的 input 元素 | +| `:read-only` | `input:read-only` | 选择指定了 "readonly" 属性的 input 元素 | +| `:read-write` | `input:read-write` | 选择未指定 "readonly" 属性的 input 元素 | +| `:required` | `input:required` | 选择指定了 "required" 属性的 input 元素 | +| `:root` | `:root` | 选择文档的根元素 | +| `::selection` | `::selection` | 选择用户选中的元素部分 | +| `:target` | `#news:target` | 选择当前激活的 #news 元素(点击了包含该锚点名称的 URL) | +| `:valid` | `input:valid` | 选择所有值有效的 input 元素 | +| `:visited` | `a:visited` | 选择所有已访问的链接 | diff --git a/src/tools/docker-compose-memo/docker-compose-memo.vue b/src/tools/docker-compose-memo/docker-compose-memo.vue index c455b35b00..8a18c41d01 100644 --- a/src/tools/docker-compose-memo/docker-compose-memo.vue +++ b/src/tools/docker-compose-memo/docker-compose-memo.vue @@ -1,13 +1,36 @@ diff --git a/src/tools/docker-compose-memo/docker-compose.zh.md b/src/tools/docker-compose-memo/docker-compose.zh.md new file mode 100644 index 0000000000..68ea68b7ea --- /dev/null +++ b/src/tools/docker-compose-memo/docker-compose.zh.md @@ -0,0 +1,462 @@ +Docker Compose 是一个用于定义和运行多容器 Docker 应用程序的强大工具。它使用一个 YAML 文件(`compose.yaml`)来配置应用服务、网络、卷等。该文件允许开发者以声明式的方式描述基础设施和依赖关系,从而更轻松地管理复杂的环境。 + +无论你是在搭建本地开发环境,还是部署到生产环境,Compose 都能简化编排过程,并让你的配置保持可读、可版本控制。 + +## 📁 文件名 +```yaml +compose.yaml +``` + +### ✅ YAML 格式规则 + +- 缩进使用 **2 个空格**(不要使用制表符) +- 键和值是 **区分大小写** 的 +- 列表使用 `-` 表示每一项 +- 包含特殊字符的字符串应使用引号括起来 +- 环境变量可以内联定义,也可以通过 `.env` 文件定义 + +## 🧱 基本结构 + +```yaml +services: + service_name: + image: image_name:tag + build: + context: . + dockerfile: Dockerfile + ports: + - "host_port:container_port" + volumes: + - ./host_path:/container_path + environment: + - VAR_NAME=value + depends_on: + - other_service + networks: + - custom_network +networks: + custom_network: + driver: bridge +volumes: + custom_volume: +``` + +## ⚙️ 服务(Services) + +每个 service 都定义一个容器。 + +### 常用服务选项 + +```yaml +services: + web: + image: nginx:latest + build: + context: ./app + dockerfile: Dockerfile + command: ["nginx", "-g", "daemon off;"] + container_name: custom_name + ports: + - "8080:80" + expose: + - "80" + environment: + - DEBUG=true + env_file: + - .env + volumes: + - ./data:/data + restart: always + depends_on: + - db + networks: + - frontend + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost"] + interval: 30s + timeout: 10s + retries: 5 +``` + +## 🏗️ 构建选项(Build Options) + +```yaml +build: + context: ./dir + dockerfile: Dockerfile + args: + build_arg: value + target: build-stage +``` + +- **`build:`** 告诉 Compose 如何构建镜像。 + - `context:` 是包含 Dockerfile 和源代码的目录。 + - `dockerfile:` 允许你指定自定义的 Dockerfile 名称或路径。 + +## 📦 卷(Volumes) + +```yaml +volumes: + data_volume: + driver: local + driver_opts: + type: none + device: /path/on/host + o: bind +``` + +### 挂载卷 + +```yaml +volumes: + - data_volume:/app/data + - ./local:/container/path +``` + +- **`volumes:`** 将宿主机目录或具名卷挂载到容器中。 + - `./src:/app/src` 将本地的 `src` 文件夹挂载到容器中的 `/app/src`。 + +## 🌐 网络(Networks) + +```yaml +networks: + frontend: + driver: bridge + backend: + driver: overlay +``` + +- **`networks:`** 将服务连接到一个或多个自定义网络。可实现服务发现和隔离。 + +### 为服务分配网络 + +```yaml +services: + app: + networks: + - frontend + - backend +``` + +## 🌐 端口(Ports) + +```yaml + ports: + - "3000:3000" +``` +- **`ports:`** 将容器端口映射到宿主机端口。格式为 `"宿主机:容器"`。常用于将服务暴露给本机访问。 + +## 🔐 密钥(Secrets,仅 Docker Swarm) + +```yaml +secrets: + db_password: + file: ./db_password.txt + +services: + db: + secrets: + - db_password +``` + +## 🔑 配置(Configs,仅 Docker Swarm) + +```yaml +configs: + my_config: + file: ./config.txt + +services: + app: + configs: + - source: my_config + target: /etc/config.txt +``` + +## 🧪 健康检查(Healthcheck) + +```yaml +healthcheck: + test: ["CMD", "curl", "-f", "http://localhost"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s +``` + +- **`healthcheck:`** 定义 Docker 如何检查容器是否健康。 + - `test:` 要运行的命令 + - `interval:` 检查的间隔时间 + - `timeout:` 等待响应的超时时间 + - `retries:` 在标记为不健康之前允许失败的次数 + +## 🔄 重启策略(Restart Policies) + +```yaml +restart: no # 从不重启 +restart: always # 总是重启 +restart: on-failure # 失败时重启 +restart: unless-stopped +``` + +## 🧬 环境变量(Environment Variables) + +```yaml +environment: + - VAR1=value1 + - VAR2=value2 +env_file: + - .env +``` + +- **`environment:`** 在容器内设置环境变量。常用于配置。 +- **`env_file:`** 从文件加载环境变量。可以将密钥和配置与 Compose 文件分离。 + +## 命令(Command) + +```yaml + command: npm start +``` +- **`command:`** 覆盖 Dockerfile 中定义的默认命令。常用于自定义容器行为。 + +## 依赖(Dependencies) + +```yaml + depends_on: + - db +``` +- **`depends_on:`** 指定服务的启动顺序。在 Compose 中,这并不会等待服务"就绪"——只是"已启动"。 + +## 🧹 清理(Clean Up) + +```bash +docker compose down # 停止并删除容器、网络、卷 +docker compose down -v # 同时删除具名卷 +``` + +## 🚀 命令(Commands) + +| 命令 | 描述 | +|--------|-------------| +| `docker compose up` | 启动服务 | +| `docker compose up -d` | 以分离(后台)模式启动 | +| `docker compose down` | 停止并删除服务 | +| `docker compose build` | 构建镜像 | +| `docker compose ps` | 列出容器 | +| `docker compose logs` | 查看日志 | +| `docker compose exec ` | 在容器中执行命令 | +| `docker compose config` | 校验并查看配置 | + +## 🧠 挂载 GPU / iGPU + +Docker Compose 通过 `device_requests` 字段支持 GPU 访问(Compose v3.8+ 和 Docker 19.03+)。 + +### ✅ NVIDIA GPU 示例 + +```yaml +services: + gpu-app: + image: nvidia/cuda:11.0-base + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] +``` + +### ✅ Intel iGPU(通过 VAAPI 或 OpenCL) + +```yaml +services: + igpu-app: + image: intel/openvino + devices: + - /dev/dri:/dev/dri +``` + +> 🔧 请确保你的宿主机上安装了必要的驱动和运行时(例如 NVIDIA Container Toolkit 或 Intel Media SDK)。 + +## 🔄 Compose 与 Swarm YAML 差异 + +| 特性 | Docker Compose (`compose.yaml`) | Docker Swarm (`stack.yml`) | +|--------------------|----------------------------------------|-----------------------------| +| `restart` | ✅ 支持 | ❌ 不支持 | +| `depends_on` | ✅ 支持 | ❌ 不支持 | +| `deploy` | ❌ 忽略 | ✅ 副本数必需 | +| `build` | ✅ 支持 | ❌ 不支持 | +| `volumes`(bind) | ✅ 支持 | ✅ 支持 | +| `configs` / `secrets`| ❌ 忽略 | ✅ 支持 | +| `healthcheck` | ✅ 支持 | ✅ 支持 | + +> 🧠 **提示:** 本地开发请使用 `compose.yaml`,Swarm 部署请使用 `stack.yml`。 + +## 🧬 Profiles(Compose v3.9+) + +Profiles 允许根据当前激活的 profile 有条件地包含服务。这对于区分 dev / test / staging 环境非常有用。 + +### ✅ 定义 Profiles + +```yaml +services: + web: + image: nginx + profiles: + - default + + debug: + image: busybox + command: top + profiles: + - debug +``` + +### ✅ 激活 Profiles + +```bash +docker compose --profile debug up +``` + +### ✅ 注意事项 + +- 没有 `profiles` 键的服务始终会被包含。 +- 多个 profile 可以同时激活。 +- 适用于功能开关、可选服务或针对不同环境的配置。 + +## ⚔️ YAML 差异:Docker Compose 与 Docker Swarm 模式 + +Docker Compose 和 Docker Swarm 都使用 YAML 文件来定义服务,但它们用途不同,支持的特性也不同。Compose 针对本地开发和测试进行了优化,而 Swarm 则是为跨集群的生产级编排而设计。 + +### 🧭 用途 + +| 模式 | 用途 | +|-------------|-----------------------------------| +| Compose | 本地开发、测试 | +| Swarm | 集群部署、扩缩容 | + +### 🧩 YAML 结构上的关键差异 + +| 特性 | Compose (`compose.yaml`) | Swarm (`stack.yml`) | +|----------------------|-------------------------------|----------------------| +| `build:` | ✅ 支持 | ❌ 忽略 | +| `restart:` | ✅ 支持 | ❌ 忽略 | +| `depends_on:` | ✅ 支持 | ❌ 忽略 | +| `deploy:` | ❌ 忽略 | ✅ 扩缩容、调度必需 | +| `configs:` | ❌ 忽略 | ✅ 支持 | +| `secrets:` | ❌ 忽略 | ✅ 支持 | +| `healthcheck:` | ✅ 支持 | ✅ 支持 | +| `volumes:`(bind) | ✅ 支持 | ✅ 支持 | +| `networks:` | ✅ 支持 | ✅ 支持 | +| `profiles:` | ✅ 支持(v3.9+) | ❌ 不支持 | + +### 🔧 仅 Compose 支持的特性 + +以下特性对本地开发很有用,但在 Swarm 中会被忽略: + +#### `build:` +```yaml +services: + app: + build: + context: . + dockerfile: Dockerfile +``` +- Compose 在本地构建镜像。 +- Swarm 要求使用已推送到镜像仓库的预构建镜像。 + +#### `restart:` +```yaml +restart: unless-stopped +``` +- Compose 使用此配置自动重启容器。 +- Swarm 使用 `deploy.restart_policy`。 + +#### `depends_on:` +```yaml +depends_on: + - db +``` +- Compose 按顺序启动服务。 +- Swarm 会忽略此配置;请使用 healthcheck 和 wait-for-it 脚本。 + +### 🛡️ 仅 Swarm 支持的特性 + +以下特性是 Swarm 独有的,Compose 会忽略: + +#### `deploy:` +```yaml +services: + app: + deploy: + replicas: 3 + placement: + constraints: + - node.role == manager + restart_policy: + condition: on-failure +``` +- 用于在集群中控制扩缩容、调度和重启行为。 + +#### `configs:` 和 `secrets:` +```yaml +configs: + app_config: + file: ./config.yml + +secrets: + db_password: + file: ./password.txt +``` +- 用于在节点间安全地分发配置和密钥。 + +#### `placement:`(位于 `deploy` 内) +```yaml +placement: + constraints: + - node.labels.env == production +``` +- 根据 label 将服务分配到指定节点。 + +### 🧪 健康检查(两者均支持) + +```yaml +healthcheck: + test: ["CMD", "curl", "-f", "http://localhost"] + interval: 30s + timeout: 10s + retries: 3 +``` +- 在 Compose 和 Swarm 中均可使用。 +- 在 Swarm 中,健康状态会影响服务的重新调度。 + +### 📦 卷的差异 + +| 类型 | Compose | Swarm | +|-------------|---------|-------| +| Bind mount(绑定挂载) | ✅ | ✅ | +| Named volume(具名卷)| ✅ | ✅ | +| External volume(外部卷) | ✅ | ✅ | +| Volume driver options(卷驱动选项) | ✅ | ✅ | + +Swarm 要求外部卷必须预先在所有节点上创建好。 + +### 🧠 总结 + +| 特性类别 | Compose | Swarm | +|----------------------|---------|-------| +| 本地构建 | ✅ | ❌ | +| 集群扩缩容 | ❌ | ✅ | +| Secrets / Configs | ❌ | ✅ | +| Profiles | ✅ | ❌ | +| 重启策略 | ✅ | ✅(通过 `deploy`) | +| 服务依赖 | ✅ | ❌ | + +> 🧭 **提示:** 开发请使用 `compose.yaml`,Swarm 请使用 `stack.yml`。你也可以将配置拆分为多个文件,或使用 `kompose` 等工具将 Kubernetes 的清单进行转换。 + +## 📚 资源 + +- [Compose 文件参考](https://docs.docker.com/compose/compose-file/) +- [Docker CLI 参考](https://docs.docker.com/engine/reference/commandline/compose/) +- [NVIDIA GPU 支持](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) +- [Intel GPU 支持](https://github.com/intel/media-driver) diff --git a/src/tools/docker-memo/docker-memo.vue b/src/tools/docker-memo/docker-memo.vue index f8880a1de7..318886c19e 100644 --- a/src/tools/docker-memo/docker-memo.vue +++ b/src/tools/docker-memo/docker-memo.vue @@ -1,13 +1,36 @@ diff --git a/src/tools/docker-memo/docker.zh.md b/src/tools/docker-memo/docker.zh.md new file mode 100644 index 0000000000..efa987a21d --- /dev/null +++ b/src/tools/docker-memo/docker.zh.md @@ -0,0 +1,482 @@ +Docker 能够将应用程序打包并运行在一个称为容器(container)的松散隔离环境中。这种隔离性和安全性使你可以在同一台主机上同时运行多个容器。容器十分轻量,包含了运行应用所需的一切,因此你无需依赖主机上当前已安装的内容。你可以在工作时轻松地共享容器,并确保每一位共享对象都能获得以相同方式运行的相同容器。 + +## 安装与资源 + +- Docker Desktop(Mac、Linux、Windows):https://docs.docker.com/desktop +- 使用 Docker 的示例项目:https://github.com/docker/awesome-compose +- 官方文档:https://docs.docker.com + +## 通用命令 + +启动 Docker 守护进程: +```bash +dockerd +``` + +获取 Docker 帮助(适用于所有子命令,例如 `docker run --help`): +```bash +docker --help +``` + +显示系统级信息: +```bash +docker info +``` + +显示 Docker 版本(客户端和服务端): +```bash +docker version +``` + +## 镜像 + +Docker 镜像是一种轻量、独立、可执行的软件包,包含运行应用所需的一切:代码、运行时、系统工具、系统库和设置。 + +从当前目录的 Dockerfile 构建镜像: +```bash +docker build -t . +``` + +不使用缓存构建镜像: +```bash +docker build -t . --no-cache +``` + +使用指定标签构建(例如 `myapp:v1.2`): +```bash +docker build -t : . +``` + +列出本地镜像: +```bash +docker images +``` + +为推送到镜像仓库给镜像打标签: +```bash +docker tag /: +``` + +删除镜像: +```bash +docker rmi +``` + +移除悬空(未使用)的镜像: +```bash +docker image prune +``` + +移除所有未使用的镜像,而不仅仅是悬空镜像: +```bash +docker image prune -a +``` + +显示镜像的各个层: +```bash +docker history +``` + +## Docker Hub + +Docker Hub 是一项用于查找和共享容器镜像的服务。了解更多请访问 https://hub.docker.com + +登录 Docker Hub: +```bash +docker login -u +``` + +登出: +```bash +docker logout +``` + +在 Docker Hub 中搜索镜像: +```bash +docker search +``` + +从 Docker Hub 拉取镜像: +```bash +docker pull +``` + +拉取指定标签的版本: +```bash +docker pull : +``` + +将镜像发布到 Docker Hub: +```bash +docker push / +``` + +## 容器 + +容器是 Docker 镜像的运行时实例。无论基础设施如何,容器都会以相同的方式运行。容器将软件与其环境隔离,确保它在开发、预发布和生产环境中保持一致的运行效果。 + +### 运行容器 + +从镜像创建并运行容器: +```bash +docker run +``` + +使用自定义名称运行: +```bash +docker run --name +``` + +在后台运行(分离模式): +```bash +docker run -d +``` + +以交互方式运行并进入 shell: +```bash +docker run -it bash +``` + +容器退出时自动移除: +```bash +docker run --rm +``` + +将容器的端口发布到主机: +```bash +docker run -p : +``` + +设置环境变量: +```bash +docker run -e KEY=value +``` + +从文件加载环境变量: +```bash +docker run --env-file ./env.list +``` + +挂载命名卷: +```bash +docker run -v :/path/in/container +``` + +将当前目录进行绑定挂载: +```bash +docker run -v $(pwd):/app +``` + +设置重启策略(可选值:`no`、`on-failure`、`always`、`unless-stopped`): +```bash +docker run --restart unless-stopped +``` + +连接到指定网络: +```bash +docker run --network +``` + +### 管理容器 + +列出正在运行的容器: +```bash +docker ps +``` + +列出所有容器(运行中和已停止): +```bash +docker ps -a +``` + +启动一个已停止的容器: +```bash +docker start +``` + +停止一个正在运行的容器: +```bash +docker stop +``` + +重启容器: +```bash +docker restart +``` + +移除一个已停止的容器: +```bash +docker rm +``` + +强制移除一个正在运行的容器: +```bash +docker rm -f +``` + +移除所有已停止的容器: +```bash +docker container prune +``` + +重命名容器: +```bash +docker rename +``` + +### 检查与交互 + +进入正在运行容器的 shell: +```bash +docker exec -it bash +``` + +对于不自带 bash 的精简镜像(例如 alpine),使用 `sh`: +```bash +docker exec -it sh +``` + +获取日志: +```bash +docker logs +``` + +持续跟踪日志(类似 `tail -f`): +```bash +docker logs -f +``` + +仅显示最后 100 行: +```bash +docker logs --tail 100 +``` + +显示容器的底层详细信息(JSON): +```bash +docker inspect +``` + +实时查看所有容器的资源使用统计: +```bash +docker stats +``` + +显示容器内正在运行的进程: +```bash +docker top +``` + +从容器中复制文件出来: +```bash +docker cp :/path/in/container ./ +``` + +将文件复制到容器中: +```bash +docker cp ./local_file :/path/ +``` + +显示容器启动以来的文件系统变更: +```bash +docker diff +``` + +## 卷 + +卷(Volume)将数据持久化在容器的可写层之外,因此数据在容器被移除后仍然保留。 + +创建命名卷: +```bash +docker volume create +``` + +列出卷: +```bash +docker volume ls +``` + +显示卷的详细信息: +```bash +docker volume inspect +``` + +移除卷: +```bash +docker volume rm +``` + +移除所有未使用的卷: +```bash +docker volume prune +``` + +将命名卷挂载到容器(由 Docker 管理): +```bash +docker run -v :/data +``` + +将主机路径绑定挂载到容器: +```bash +docker run -v $(pwd):/app +``` + +使用 `--mount` 语法的等价绑定挂载: +```bash +docker run --mount type=bind,src=$(pwd),dst=/app +``` + +## 网络 + +同一网络中的容器可以通过容器名称相互访问。 + +列出网络: +```bash +docker network ls +``` + +创建网络: +```bash +docker network create +``` + +显示网络详细信息: +```bash +docker network inspect +``` + +将正在运行的容器连接到网络: +```bash +docker network connect +``` + +将容器从网络断开: +```bash +docker network disconnect +``` + +移除网络: +```bash +docker network rm +``` + +移除所有未使用的网络: +```bash +docker network prune +``` + +## Docker Compose + +Compose 通过单个 `compose.yaml`(或 `docker-compose.yml`)文件运行多容器应用。 + +启动所有服务(前台): +```bash +docker compose up +``` + +启动所有服务(分离模式): +```bash +docker compose up -d +``` + +启动前先重新构建镜像: +```bash +docker compose up --build +``` + +停止并移除容器和网络: +```bash +docker compose down +``` + +同时移除命名卷: +```bash +docker compose down -v +``` + +列出项目中的服务: +```bash +docker compose ps +``` + +持续跟踪所有服务的日志: +```bash +docker compose logs -f +``` + +持续跟踪单个服务的日志: +```bash +docker compose logs -f +``` + +构建(或重新构建)服务: +```bash +docker compose build +``` + +拉取服务镜像: +```bash +docker compose pull +``` + +在正在运行的服务中打开 shell: +```bash +docker compose exec bash +``` + +在新容器中运行一次性命令: +```bash +docker compose run --rm +``` + +重启单个服务: +```bash +docker compose restart +``` + +校验并查看解析后的 compose 文件: +```bash +docker compose config +``` + +## 系统与清理 + +磁盘占用会迅速累积。以下命令可用于回收空间。 + +显示磁盘使用情况(镜像、容器、卷、构建缓存): +```bash +docker system df +``` + +移除已停止的容器、悬空镜像和未使用的网络: +```bash +docker system prune +``` + +同时移除所有未使用的镜像(不仅仅是悬空镜像): +```bash +docker system prune -a +``` + +同时移除未使用的卷(具有破坏性——运行前请再三确认): +```bash +docker system prune -a --volumes +``` + +清理构建缓存: +```bash +docker builder prune +``` + +## 快速参考:常用标志 + +| 标志 | 含义 | +|------|---------| +| `-d` | 分离模式(在后台运行) | +| `-it` | 交互模式 + TTY(用于 shell) | +| `--rm` | 容器退出时移除它 | +| `-p host:container` | 发布端口 | +| `-v src:dst` | 挂载卷或绑定挂载 | +| `-e KEY=value` | 环境变量 | +| `--name` | 指定容器名称 | +| `--network` | 连接到网络 | +| `--restart` | 重启策略(`no`、`on-failure`、`always`、`unless-stopped`) | diff --git a/src/tools/docker-swarm-memo/docker-swarm-memo.vue b/src/tools/docker-swarm-memo/docker-swarm-memo.vue index e005c16ef4..2c77489bc9 100644 --- a/src/tools/docker-swarm-memo/docker-swarm-memo.vue +++ b/src/tools/docker-swarm-memo/docker-swarm-memo.vue @@ -1,13 +1,36 @@ diff --git a/src/tools/docker-swarm-memo/docker-swarm.zh.md b/src/tools/docker-swarm-memo/docker-swarm.zh.md new file mode 100644 index 0000000000..f038495cc3 --- /dev/null +++ b/src/tools/docker-swarm-memo/docker-swarm.zh.md @@ -0,0 +1,200 @@ +**Docker Swarm 模式** 是 Docker 原生的集群与编排解决方案。它允许你将一组 Docker 节点作为一个虚拟系统统一管理,从而实现高可用性、负载均衡以及容器化应用的简化部署。 + +主要特性: +- 内置编排 +- 声明式服务模型 +- 滚动更新 +- 自动扩缩容与自愈 +- 通过 TLS 实现安全的节点通信 + +## 📌 Swarm 初始化 + +- **初始化 Swarm** + ```bash + docker swarm init + ``` + +- **加入 Swarm(在工作节点/管理节点上)** + ```bash + docker swarm join-token worker + ``` + +- **离开 Swarm** + ```bash + docker swarm leave + ``` + +- **强制离开(在管理节点上)** + ```bash + docker swarm leave --force + ``` + +## 👥 节点管理 + +- **列出节点** + ```bash + docker node ls + ``` + +- **将节点提升为管理节点** + ```bash + docker node promote + ``` + +- **将节点降级为工作节点** + ```bash + docker node demote + ``` + +- **查看节点详情** + ```bash + docker node inspect --pretty + ``` + +- **排空节点(禁止调度)** + ```bash + docker node update --availability drain + ``` + +- **激活节点** + ```bash + docker node update --availability active + ``` + +## 🧠 管理节点 + +管理节点负责: +- 编排任务与服务 +- 维护集群状态 +- 处理 API 请求 + +你可以部署多个管理节点以实现高可用性,但任意时刻只有一个是 **leader(领导者)**。 + +- **查看管理节点状态** + ```bash + docker node ls + ``` + +- **查看 Raft 共识信息** + ```bash + docker swarm inspect + ``` + +## 📦 服务管理 + +- **创建服务** + ```bash + docker service create --name + ``` + +- **创建带副本的服务** + ```bash + docker service create --name --replicas + ``` + +- **列出服务** + ```bash + docker service ls + ``` + +- **查看服务详情** + ```bash + docker service inspect --pretty + ``` + +- **扩缩容服务** + ```bash + docker service scale = + ``` + +- **更新服务** + ```bash + docker service update --image + ``` + +- **删除服务** + ```bash + docker service rm + ``` + +## 🔁 副本(Replicas) + +副本定义了某个服务在 Swarm 集群中应运行的实例数量。 + +- **创建服务时设置副本数** + ```bash + docker service create --replicas 5 --name myapp myimage + ``` + +- **扩缩容副本** + ```bash + docker service scale myapp=10 + ``` + +Swarm 会自动将副本分配到可用的节点上,并在副本失败时自动重启。 + +## 🐝 任务与容器管理 + +- **列出服务的任务** + ```bash + docker service ps + ``` + +- **列出所有任务** + ```bash + docker node ps + ``` + +- **列出容器** + ```bash + docker container ls + ``` + +- **查看容器详情** + ```bash + docker container inspect + ``` + +## 🌐 网络 + +### 🧠 什么是覆盖网络(Overlay Network)? +覆盖网络(overlay network)是一种跨越多个 Docker 主机的虚拟网络。它允许运行在不同节点上的容器 + +### 命令 + +- **创建覆盖网络** + ```bash + docker network create --driver overlay + ``` + +- **列出网络** + ```bash + docker network ls + ``` + +- **将服务连接到网络** + ```bash + docker service create --name --network + ``` + +## 🛠 常用参数 + +| 参数 | 说明 | +|------|------| +| `--replicas` | 服务实例的数量 | +| `--publish` | 端口映射(`:`) | +| `--mount` | 卷挂载 | +| `--constraint` | 节点放置规则 | +| `--update-delay` | 更新之间的延迟 | +| `--limit-cpu` / `--limit-memory` | 资源限制 | + +## 📄 示例:创建一个 Web 服务 + +```bash +docker service create \ + --name web \ + --replicas 3 \ + --publish 80:80 \ + --network webnet \ + nginx +``` diff --git a/src/tools/dockerfile-memo/dockerfile-memo.vue b/src/tools/dockerfile-memo/dockerfile-memo.vue index 734d588262..c1ec6edd86 100644 --- a/src/tools/dockerfile-memo/dockerfile-memo.vue +++ b/src/tools/dockerfile-memo/dockerfile-memo.vue @@ -1,13 +1,36 @@ diff --git a/src/tools/dockerfile-memo/dockerfile.zh.md b/src/tools/dockerfile-memo/dockerfile.zh.md new file mode 100644 index 0000000000..5da6296a64 --- /dev/null +++ b/src/tools/dockerfile-memo/dockerfile.zh.md @@ -0,0 +1,258 @@ +**Dockerfile** 是一个由指令组成的脚本,用于构建 Docker 镜像。每条指令都会在镜像中创建一个层。 + +## 📦 基本结构 + +```Dockerfile +# 注释 +INSTRUCTION arguments +``` + +## 🚀 核心指令 + +### `FROM` +指定基础镜像。 + +```Dockerfile +FROM ubuntu:20.04 +FROM node:22-alpine +``` + +### `LABEL` +为镜像添加元数据。 + +```Dockerfile +LABEL maintainer="you@example.com" +LABEL version="1.0" description="My App" +``` + +### `ENV` +设置环境变量。 + +```Dockerfile +ENV NODE_ENV=production +ENV PATH="/app/bin:$PATH" +``` + +### `RUN` +在构建过程中于 shell 中执行命令。 + +```Dockerfile +RUN apt-get update && apt-get install -y curl +RUN npm install +``` + +使用 `RUN ["executable", "param1", "param2"]` 以 JSON 数组形式书写。 + +### `COPY` +将文件从主机复制到镜像中。 + +```Dockerfile +COPY . /app +COPY config.json /app/config.json +``` + +### `ADD` +类似于 `COPY`,但支持远程 URL 并可自动解压归档文件。 + +```Dockerfile +ADD https://example.com/file.tar.gz /app/ +ADD archive.zip /app/ +``` + +### `CMD` +设置容器启动时运行的默认命令。 + +```Dockerfile +CMD ["node", "server.js"] # 推荐的 exec 形式 +CMD node server.js # shell 形式 +``` + +只允许一条 `CMD`;后面的会覆盖前面的。 + +### `ENTRYPOINT` +将容器配置为可执行程序运行。 + +```Dockerfile +ENTRYPOINT ["python", "app.py"] +``` + +与 `CMD` 搭配使用可传递默认参数。 + +### `WORKDIR` +为后续指令设置工作目录。 + +```Dockerfile +WORKDIR /app +``` + +### `EXPOSE` +声明容器监听的端口。 + +```Dockerfile +EXPOSE 80 +EXPOSE 443 +``` + +注意:这并不会发布端口。 + +### `VOLUME` +为持久化或共享数据创建挂载点。 + +```Dockerfile +VOLUME ["/data"] +``` + +### `USER` +设置运行后续指令的用户。 + +```Dockerfile +USER appuser +``` + +### `ARG` +定义构建时变量。 + +```Dockerfile +ARG VERSION=1.0 +RUN echo $VERSION +``` + +在 `docker build` 时使用 `--build-arg VERSION=2.0`。 + +### `ONBUILD` +当该镜像被用作基础镜像时触发相应指令。 + +```Dockerfile +ONBUILD COPY . /app +``` + +## 🧠 最佳实践 + +- 使用精简的基础镜像(例如 `alpine`)以减小体积。 +- 合并 `RUN` 命令以减少层数。 +- 使用 `.dockerignore` 排除不必要的文件。 +- 除非需要解压归档,否则优先使用 `COPY` 而非 `ADD`。 +- 使用 `ENTRYPOINT` 定义固定命令,使用 `CMD` 传递参数。 +- 避免硬编码密钥或凭据。 + +## 🧪 示例 Dockerfile + +```Dockerfile +FROM node:22-alpine + +LABEL maintainer="guillaume@example.com" + +WORKDIR /app + +COPY package*.json ./ +RUN npm install + +COPY . . + +EXPOSE 3000 + +ENV NODE_ENV=production + +CMD ["node", "index.js"] +``` + +## 🛠️ 构建与运行 + +```bash +# 构建镜像 +docker build -t my-app . + +# 运行容器 +docker run -p 3000:3000 my-app +``` + +## 📁 .dockerignore 示例 + +```plaintext +node_modules +*.log +Dockerfile +.git +``` + +## 🏗️ 多阶段构建 + +**多阶段构建**允许你在一个 Dockerfile 中使用多条 `FROM` 语句,以优化镜像体积并将构建依赖与运行时分离。 + +### 🎯 为什么使用多阶段构建? + +- 通过排除构建工具和中间文件来减小最终镜像体积。 +- 通过最小化攻击面来提升安全性。 +- 保持 Dockerfile 简洁且易于维护。 + +### 🧱 基本语法 + +```Dockerfile +# 阶段 1:构建 +FROM node:22-alpine AS builder +WORKDIR /app +COPY package*.json ./ +RUN npm install +COPY . . +RUN npm run build + +# 阶段 2:生产 +FROM nginx:alpine +COPY --from=builder /app/dist /usr/share/nginx/html +``` + +### 🏷️ 命名阶段 + +你可以使用 `AS ` 为每个阶段命名,并在之后通过 `--from=` 引用它。 + +```Dockerfile +FROM golang:1.21 AS build +WORKDIR /src +COPY . . +RUN go build -o myapp + +FROM alpine:latest +COPY --from=build /src/myapp /usr/local/bin/myapp +ENTRYPOINT ["myapp"] +``` + +### 📦 复制构建产物 + +使用 `COPY --from=` 将文件从一个阶段复制到另一个阶段。 + +```Dockerfile +COPY --from=builder /app/output /app/output +``` + +你可以复制: +- 文件 +- 目录 +- 二进制文件 +- 配置 + +### 🧼 精简的最终镜像 + +多阶段构建可帮助你避免臃肿的镜像: + +```Dockerfile +# 不使用多阶段:包含编译器、源代码等 +# 使用多阶段:仅包含运行时必需项 +``` + +### 🧪 实战示例:React 应用 + +```Dockerfile +# 构建阶段 +FROM node:22 AS build +WORKDIR /app +COPY package*.json ./ +RUN npm install +COPY . . +RUN npm run build + +# 服务阶段 +FROM nginx:alpine +COPY --from=build /app/build /usr/share/nginx/html +EXPOSE 80 +CMD ["nginx", "-g", "daemon off;"] +```