Invincibility (god mode)
Turn on god mode with the /gamemode creative command or the Resistance effect.
Commands
/gamemode creative Switches you to Creative mode, where you take no damage
/effect give @s minecraft:resistance 999999 255 true Gives you full damage resistance for a very long time
/effect give @s minecraft:regeneration 999999 255 true Regenerates your health instantly, which makes you almost immortal
How it works
There are several ways to become immortal (god mode) in Minecraft. The simplest is to switch to Creative mode, where you take no damage from any source except the /kill command and falling into the void below Y=-64. Alternatively, you can give yourself the Resistance effect at its highest level, which reduces damage to zero. The /effect command gives you full control over how long an effect lasts: set the duration to 999,999 seconds and it lasts practically forever. On multiplayer servers, admins often use plugins such as Essentials, which offer the /god command as a handy shortcut.
Practical tips
Creative mode doesn't protect you from /kill or the void.
The 'true' parameter at the end of the /effect command hides the effect's particles.
In Bedrock, the syntax is: /effect @s resistance 999999 255 true.
Resistance 255 combined with Regeneration 255 gives you the most complete protection.