IPsec VPNs exchange information through logical connections called SAs (Security Associations). An SA is simply a definition of the protocols, algorithms and key validity time period used by endpoints. Each IPsec VPN has two SAs -- one in each direction. SAs are identified by three identifiers. One of them is a unique number called the SPI (Security Parameter Index), which is assigned by destination to each SA. The other two identifiers are the destination address and the protocol. The uniqueness of the SPI is guaranteed because a destination endpoint may have a manually configured SPI defined that the originator would not know about.
Finally, the IKE (Internet Key Exchange) is a separate SA that is used to negotiate the other IPsec protocol parameters. IKE uses UDP Port 500 and as such can be passed through a NAT without any special handling, like any other TCP/UDP protocol. IKE is active during the entire lifetime of the lower-level SA.
Gimme the Good Stuff
Now here is where things get interesting. Let's look at some cases in which IPsec and NAT fail. NAT and AH IPsec will fail because,, by definition, NAT changes the IP addressing of the IP packet. Any change in the IP packet will be flagged as a violation by AH. Failure also occurs when there is a NAPT function between the two IPsec endpoints that doesn't know how to handle IPsec traffic.
Likewise, ESP IPsec and NAPT will fail, because in the case of transport mode, the port numbers are protected by ESP, and any change will be flagged as a violation.