Skip to content

Instantly share code, notes, and snippets.

@bingzhangdai
Last active March 3, 2024 03:19
Show Gist options
  • Save bingzhangdai/c71569aa5ad97ca928d24470326e06ee to your computer and use it in GitHub Desktop.
Save bingzhangdai/c71569aa5ad97ca928d24470326e06ee to your computer and use it in GitHub Desktop.
Common settings for WSL

The common settings for WSL

These are recommended steps for setting up your WSL

Mount disk C: with "metadata" flag

This will allow users to set the owner and group of files using chmod/chown and modify read/write/execute permissions in WSL.

  1. unmount drvfs
sudo umount /mnt/c
  1. remount it with the "metadata" flag
sudo mount -t drvfs C: /mnt/c -o metadata
  1. mount automatically with "metadata" enabled

sudo vi /etc/wsl.conf and add the following lines,

# mount with options
[automount]
options = "metadata"
[boot]
systemd=true

Set WSL to use your Windows home directory

It would be very convenient to keep home in sync among Windows and different WSL distros.

  1. change home path

sudo vi /etc/passwd and find the line defines your username. It will look like this,

david:x:1000:1000:,,,:/home/david:/bin/bash

Change it to,

david:x:1000:1000:,,,:/mnt/c/users/bindai:/bin/bash
  1. change permission

Exit WSL and re-open it. Home is now changed to new path. Then set home directory permission.

chown david ~
chgrp david ~
chmod 755 ~

How to start SSH server under WSL

  1. install openssh server
sudo apt update
sudo apt install openssh-server
  1. generate hostkeys
sudo dpkg-reconfigure openssh-server
  1. edit the /etc/ssh/sshd_config configuration file to allow password authentication
PasswordAuthentication yes
  1. restart the ssh server
sudo service ssh --full-restart

Fix WSL2 DNS resolution

It is convenient to use the same DNS server with the Window host.

  1. sudo vi /etc/wsl.conf and add the following lines,
[network]
generateResolvConf = false

restart wsl2: wsl --terminate $WSL_DISTRO_NAME.

  1. get the name servers and optional the search domain
ipconfig /all | grep "DNS Servers" | awk '{print "nameserver " $NF}'
ipconfig /all | grep -Po "DNS Suffix .* : \K([^\s]+)" | sort | uniq

sudo vi /etc/resolv.conf and put the above nameservers.

restart wsl2: wsl --terminate $WSL_DISTRO_NAME.

Run ping or other tools without sudo

If you directly run ping, you will probably get ping: socket: Operation not permitted. This usually happens in WSL1. Below command will fix

sudo chmod u+s `which ping`

Bridged networking under WSL2

  1. Create an external switch in Hyper-v, say Bridge-WSL.

  2. Create a file named .wslconfig under %USERPROFILE% in Windows.

[wsl2]
networkingMode=bridged
vmSwitch=Bridge-WSL # change this to the bridge name just created.
ipv6=true
  1. restart wsl2: wsl --terminate $WSL_DISTRO_NAME.

Check ip a to see if it actually works.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment