Sounds like a failing battery which is not surprising as it is about 5 years old. Check the battery condition by Option-clicking the battery icon on the menubar. If you are using macOS 10.15+, then you may see "Service Recommended" if the battery has less than 80% of its design capacity or if a hardware fault has been detected with the battery. Unfortunately Apple doesn't display any condition if the battery is considered healthy. With older versions of macOS it will display "Normal" for a healthy battery, or one of three other conditions "Replace Soon", "Replace Now", or "Service Battery". Just because the battery condition is "Normal" does not mean there isn't some fault with the battery.
You can also try running the Apple Diagnostics to see if any hardware issues are detected. Again, a passing diagnostic does not mean the battery is good. If you let the battery drain until the laptop shuts off, then connect the charger & immediately run the diagnostics, then maybe it may be more likely to see a battery failure since the test is being run at the point where the battery has the problem.
That symptom is a classic one for a failing battery. Have Apple or an Apple Authorized Service Provider examine the laptop to provide you with a repair estimate.
Do you notice whether the USB-C cables feel loose in the USB-C ports? These ports tend to wear causing the USB-C cables not to fit tightly especially if you connect & disconnect items a lot. Unfortunately if they are too loose, it will require the replacement of the entire Logic Board since the connectors are integrated into the Logic Board (expensive $500+ US repair). Plus this 2017 model has other better known design defects such as bad display cable, terrible keyboard design, and the SSD in this model has a higher rate of failure than other models. Consider all these things when deciding whether the repair is economical. On the plus side, if the battery is replaced, then you will get a new Top Case Assembly which includes the palmrest, Keyboard, and Trackpad in addition to the Battery.
See if your laptop qualifies for this free battery repair program (only a few laptops will qualify, and it may already be expired for most people):
13-inch MacBook Pro (non Touch Bar) Battery Replacement Program - Apple Support
FYI, here is the current list of the publicly acknowledged free repair programs for various Apple products (some products like your laptop may have multiple programs):
Apple Service Programs - Apple Support